当通过 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);
},
});
最佳答案
这是出于安全原因由 ASP.NET 插入的。查看this article了解更多详情。
If you aren’t familiar with the “.d” I’m referring to, it is simply a security feature that Microsoft added in ASP.NET 3.5’s version of ASP.NET AJAX. By encapsulating the JSON response within a parent object, the framework helps protect against a particularly nasty XSS vulnerability.
他们有一个很好的解决方案,即使用 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;
},
关于c# - 从 C# 传输到 ExtJS 时 JSON 数据发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24147100/