JSON from Django render() to React.js



我正在编写一个简单的Django+React应用程序,我想在其中将一些JSON从Django render((传递到React.js。我首先用Django渲染一个HTML页面,提供JSON。虽然我不知道格式,但数据正在通过,因为我可以使用Django的模板语言来展示它。然而,在HTML页面调用的React代码中,我得到的JSON是一个字符串,只有前10个字符。我想知道是否有一种方法可以正确地完成这项工作,而不是每次都要写一篇http文章。

我的Django视图脚本,它呈现html:

@login_required(login_url="/login/")
def index(request):
data = {
'key': [0, 1, 2, 3],
'key2': 'abcd',
}
context = {
'data': json.dumps(data),
'navItem': 0,
}
return render(request, "index.html", context)

我的index.html:

<!DOCTYPE html>
<html lang="en">
<body>
{{data}}
<div class="reactitem" data-json={{data}}></div>
<script src="http://127.0.0.1:8080/index.js" charset="utf-8"></script>
</body>
</html>

最后是我的index.js(本地托管(:

document.querySelectorAll('#reactitem').forEach((domContainer) => {
console.log(domContainer.dataset.json);
console.log(typeof(domContainer.dataset.json));
console.log(domContainer.dataset.json.length);
})

当我加载页面时,我在屏幕上看到完整的数据json,同时在控制台中获得以下输出:

{"key":
string
7

我看到这个概念应用于大型生产解决方案。这是一种有效的方法。

给定内容已序列化为.

<div data-json='{&quot;someKey&quot;:&quot;someValue&quot;}'></div>

然后可以将其反序列化为JS对象。

const el = document.querySelector('[data-json]');
const json = JSON.parse(el.dataset.json);
console.log(json)

这在控制台中渲染{someKey: "someValue"}

HTML也可能是这样的。但是'应该被转义。

<div data-json='{"someKey":"someValue"}'></div>

最新更新