从C#转移到ExtJS时,JSON数据发生了变化

时间:2014-06-10 17:13:56

标签: c# ajax json extjs

当通过ExtJS 4.2.2中的Ajax调用从asp.net C#中的Webmethod传输JSON数据时,会在字符串的开头和结尾添加几个字符。

离开C#之前的JSON数据:

[{"ID":"0","NAME":"ALAN"},{"ID":"1","NAME":"BLAKE"}]

由ExtJS收到的firebug看到的JSON数据

{"d":"[{"ID":"0","NAME":"ALAN"},{"ID":"1","NAME":"BLAKE"}]"}

如果JSON数据具有设置的根属性,也会发生这种情况。 从它看来,似乎某个地方的某些东西将传入的数据视为JSON字符串中的变量或类似的东西。

C#结尾的代码:

[WebService(Namespace = "localhost")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Director : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = false)]
    public string getData()
    {
        string json = "[{\"ID\":\"0\",\"NAME\":\"ALAN\"},{\"ID\":\"1\",\"NAME\":\"BLAKE\"}]";
        System.Diagnostics.Debug.WriteLine(json);
        return json;
    }
}

ExtJS Ajax调用代码(已经实施了解决方法):

Ext.Ajax.request({
    async: false,
    url: Test061014.ApplicationPath + '/Director.asmx/getData',
    headers: { 'Content-Type': 'application/json' },
    scope: this,
    success: function (conn, response, options, eOpt) {
        var s = conn.responseText;
        s = s.substring(6, (s.length - 2));
        s = s.replace(/\\/g, "");
        categoryData = JSON.parse(s);
    },
});

1 个答案:

答案 0 :(得分:1)

出于安全原因,ASP.NET会插入它。查看this article了解详情。

  

如果你不熟悉我所指的“.d”,它只是一个   Microsoft在ASP.NET 3.5版本中添加的安全功能   ASP.NET AJAX。通过将JSON响应封装在父级中   对象,框架有助于防止特别讨厌的XSS   漏洞。

他们使用dataFilter属性有一个很好的解决方案,因此您可以不再担心.d。再次,归功于文章,这是他们的解决方案。您可能需要阅读文章不要让我思考部分,因为我遗漏了一些细节。

dataFilter: function(data) {
// This boils the response string down 
//  into a proper JavaScript Object().
var msg = eval('(' + data + ')');

// If the response has a ".d" top-level property,
//  return what's below that instead.
if (msg.hasOwnProperty('d'))
  return msg.d;
else
  return msg;
},
相关问题