【问题标题】:Populate a html div with json data received from a server使用从服务器接收到的 json 数据填充 html div
【发布时间】:2014-06-13 07:11:29
【问题描述】:

我需要一个 html div 填充从服务器接收的 json 数据,这是一个 json-rpc 服务器,它重新运行 application/jsson-rpc 内容类型,我可以在 chrome 和 firefox 开发工具中看到结果...我需要将其视为给定 div 内页面的一部分

我有这个脚本来填充 mybox div,但它什么也没提供

    var returnedinfo;
    var request = $.ajax ({
    url: "/url",
    type: "POST",
    data: JSON.stringify(data),
    success: function(json) {
      alert("success sent ajax");
         $("#mybox").html(json); 
         returnedinfo = json;               
   });

当请求完成时,我还绑定了 ajax 块之外的填充函数

request.done(function(msg) {
         $("#mybox").text(msg);
       });

这只是返回一个像这样的空数组

 [object Object]

没有其他帮助将不胜感激。

【问题讨论】:

  • 展示json的格式
  • 使用dataType:"json"
  • json的格式是什么意思?并且不是数据类型 json 应该用于发送的 POST 请求吗?
  • 这是一个常见问题,如果您费心用谷歌搜索,您可能已经在多个博客甚至本网站上看到了如何处理
  • @GideonMaina 使用 console.log(josn) 并查看从服务器返回的内容

标签: javascript jquery ajax json json-rpc


【解决方案1】:

您需要附加 json 项的 key

$("#mybox").html(json.key);

【讨论】:

  • 感谢 Levent 在我附加我需要的 json 项目的键后它现在可以工作了,比如 $("#mybox").html(json.result);
【解决方案2】:

将 dataType 添加到您的 ajax 请求中。

var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
success: function(json) {
  alert("success sent ajax");
     $("#mybox").html(json); 
     returnedinfo = json;               
});

【讨论】:

  • 您对 console.log(josn) 看到了什么。你能提供你的响应 json 吗?
【解决方案3】:

试试这个我的工作示例 看看 contentTypehtml 函数来替换 mybox 元素的 html

$.ajax({
    type: 'POST',
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    url: 'url',
    success: function (dataRes) {
                $('#mybox').html(dataRes);

              },
    error: function(a,b,c) {

    }
});

请注意,在这种情况下,成功函数中的 dataRes 是一个 html 字符串,例如 <strong>test</strong>

如果您的服务器端函数返回一个 json 对象,您应该将 dataType: 'json' 添加到 ajax 请求中,然后您可以使用 dataRes 对象的属性,例如 $('#mybox').html(dataRes.property1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2013-10-31
    • 2018-12-18
    • 1970-01-01
    相关资源
    最近更新 更多