如果你想从你的方法中返回 JSON,你需要使用 ScriptMethod 属性。
像这样构造你的方法,注意[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 属性。
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string MyMethod()
{
}
目前,此方法返回一个string,它可以是一个JSON 结构化字符串。但是,您可能最好返回一个对象,该对象可以解析为JSON。 List<string> 以及具有标准数据类型的类,如 integers、strings 等非常适合此。然后,您可以只返回该对象。 ScriptMethod 负责将其转换为 JSON。
例如:
你要返回的类:
public class MyJson
{
public int ID;
public List<string> SomeList;
public string SomeText;
}
以及您返回填充MyJson的方法
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public MyJson MyMethod()
{
MyJson m = new MyJson();
m.ID = 1;
m.SomeText = "Hello World!";
m.SomeList = new List<string>();
m.SomeList.Add("Foo");
m.SomeList.Add("Bar");
return m;
}
返回JSON 的结构与类一样。属性名称也将被使用,您的List<string> 将成为一个数组
使用 AJAX 调用它。本例中的 JQuery:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "/YourPage.aspx/MyMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// content will be in here... I.E
var id = msg.d.ID;
var st = msg.d.SomeText;
var sl = msg.d.SomeList;
var i = sl.length;
var firstSlItem = sl[0];
}
});
});