简而言之:
对 AJAX
调用的响应
返回 2 个 HTML
元素:script
和 div
,以 JSON
格式存储。 响应
的结构如下:
Object { script : "<script>...</script>", div : "<div></div>" }
response
包含我需要嵌入的 JSON
中的对象。我怎样才能做到这一点?我的代码:
<body>
<script type=text/javascript>
$.ajax({
url: "my.url",
type: "GET",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function(response){
// Code that embeds script and div in to the body of the document
}
});
</script>
<小时/>
更多细节:
div
包含从 script
元素引用的 3 个图表。它们都是从运行 bokeh
的 python
脚本返回的。其他一切都工作正常,我只是 HTML
和 javascript
的新手,这就是为什么我不知道如何嵌入 JSON
中的标签> 到 html 正文。
感谢您的帮助!
编辑:与here不同,我请求具体帮助,了解如何将返回的 JSON
(不带任何 div 参数)嵌入到 AJAX
函数
最佳答案
您必须通过 JSON.parse() 将 JSON 解析为对象功能
<body>
<script type=text/javascript>
$.ajax({
url: "my.url",
type: "GET",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function(response){
// Parse to object
var object_response = JSON.parse(response);
// Access object like this
var response_script = object_response.script;
// And the second one the same way
var response_div = object_response.div;
// And then, for example, you can then append that div like this
$("body").append(response_div);
}
});
</script>
编辑更改为 -> 。如下建议
第二次编辑,确实在第一种情况下您不需要 JSON.parse() ,即您正确设置 header header('Content-type:application/json');
否则评论中建议的这种技术将不起作用,您将不得不使用 JSON.parse() 函数
关于javascript - 如何嵌入以 JSON 返回的 HTML <tag>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47248005/