javascript - 如何嵌入以 JSON 返回的 HTML <tag>

标签 javascript jquery html json ajax

简而言之:

AJAX 调用的响应返回 2 个 HTML 元素:scriptdiv,以 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 个图表。它们都是从运行 bokehpython 脚本返回的。其他一切都工作正常,我只是 HTMLjavascript 的新手,这就是为什么我不知道如何嵌入 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/

相关文章:

html - css 删除继承的列表样式

php - joomla 1.5 自定义移动框架不加载 css

javascript - `toFixed()` 对某些数字无法正常工作

javascript - iPad 方向改变后页面元素放置不当

使用 PHP 进行 Javascript 客户端验证

jquery - 如何在浏览器的任意页面上直接运行jQuery?

javascript - jQUery 代码在 IE 中不起作用

javascript - 在 Canvas 上使用 HTML,没有任何效果

javascript - ajax 调用 mvc 操作中的空数据

javascript - SVG 元素边界框覆盖元素