【问题标题】:Ajax cannot read Serialized Json dictionary correctlyAjax 无法正确读取序列化 Json 字典
【发布时间】:2014-10-22 17:39:59
【问题描述】:

这就是我的 c# 代码中的内容

using Newtonsoft.Json;
.....
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("id", id.ToString());
d.Add("type", "error");
d.Add("msg", pex.Message);
.....
return JsonConvert.SerializeObject(d);

我的 AJAX

......
$.ajax({
                    type: "POST",
                    url: "Service1.svc/MyCall",
                    data: JSON.stringify(parameters),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: true,

                    beforeSend: function () {
                        $("#lblResult").html("loading");
                    },
                    success: function (data) {
                        $("#lblResult").html(data['id']);
                    },
......

这是 Firebug 中的响应

"{\"id\":\"1\",\"type\":\"error\",\"msg\":\"An exception occurred during a Ping request.\"}"

这是 Firebug 中的 JSON

0       "{"
1       """ 
2       "i"
3       "d"
4       """
5       ":"
6       """
7       "1"
8       """
9       ","
10      """
11      "t"
ETC

问题:我无法获取数据['id'] 或任何数据['SOMETHING']。

如何根据收到的回复获取它? 还有其他方法吗?

【问题讨论】:

  • 已经尝试过了,但我在 $("#lblResult").html(data['id']); - 没有细节或什么都没有

标签: c# jquery ajax json dictionary


【解决方案1】:

这看起来好像 JSON 没有正确转换回 JavaScript 对象。试试这个

success: function (data) { 
if (data.hasOwnProperty("d"))
            {
                var response = JSON.parse(data.d);
                $("#lblResult").html(response["id"]);
            }
            else
            {
                var response = JSON.parse(data);
                $("#lblResult").html(response["id"]);
            }
}

.d 是必需的,因为 .Net 出于安全原因添加了这个,比我能给出的更好的解释可以在这里找到Why do ASP.NET JSON web services return the result in 'd'?

那么由于返回值是一个JSON字符串,所以需要将其解析为Javascript Object

【讨论】:

  • 我得到 SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data - var response = JSON.parse(data.d);
  • 如果你使用 console.log data.d 会得到什么?
  • ajax在aspx页面中
  • 你也可以查看你的ajax调用的数据类型,即dataType: 'json',这里的数据类型应该是json而不是html
  • 能否用完整的 Ajax 请求更新问题,希望我们能够从那里看到问题所在
猜你喜欢
  • 1970-01-01
  • 2017-10-19
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多