【问题标题】:how to parse the json result using jquery如何使用jquery解析json结果
【发布时间】:2012-05-02 17:29:24
【问题描述】:

我有以下 ajax 调用来调用 web 服务并取回 json 数据

$(document).ready(function () {
            $.ajax({
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                url: "Test.asmx/GetImages",
                success: function (msg) {
                    //var data = JSON.parse(msg); 
                    alert(msg.d);
                   $.each(msg.results, function (i, tweet) {
                        alert(msg.d);
                        $("#imagelist").append('<p><img src="' + tweet + '" />' + tweet + '</p>');
                    });
                }
            });
 });

我有以下从 ajax 调用获得的 json 结果,我发现很难附加 img 源。

{"d":"[\r\n  {\r\n    \"imagepath\": \"images/01.jpg\"\r\n  },\r\n  {\r\n    \"imagepath\": \"images/02.jpg\"\r\n  },\r\n  {\r\n    \"imagepath\": \"images/03.jpg\"\r\n  },\r\n  {\r\n    \"imagepath\": \"images/04.jpg\"\r\n  }\r\n]"}

【问题讨论】:

标签: jquery html ajax json jquery-append


【解决方案1】:

只需指定dataType: 'json',jquery 会自动为您完成这项工作

http://api.jquery.com/jQuery.ajax/

【讨论】:

  • 感谢回复,如何分别从结果数据中提取images/01.jpg,images/02.jpg...... $.each 函数
  • @mahesh:遍历msg.d
  • 它表现得很疯狂,当我执行说 $.each({ "d": "[\r\n {\r\n \"imagepath\": \"images/01.jpg\ "\r\n },\r\n {\r\n \"imagepath\": \"images/04.jpg\"\r\n },\r\n {\r\n \"imagepath\ ": \"images/04.jpg\"\r\n },\r\n {\r\n \"imagepath\": \"images/04.jpg\"\r\n }\r\n ]" }, function (k, v) { alert("Value: " + v); });
  • @mahesh:它被触发了一次,因为您传递的对象只有一个属性,名称为d。而你需要传递数组
  • @mahesh:不,遍历msg.d,而不是msg.d.imagepath(这是第三次:-S)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 2017-05-31
  • 1970-01-01
  • 2013-06-05
相关资源
最近更新 更多