我有jQuery代码从服务器获取
JSON:
@H_404_11@$(document).ready(function () {
$.getJSON('Default2.aspx/GetPerson',{ 'firstname': 'brian','lastname': 'lee' },function (response) {
alert(response.Age);
});
});
Default2.aspx代码:
@H_404_11@[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static String GetPerson(String firstname,String lastname) { Person p = new Person(firstname,lastname); return "{\"Age\":\"12\"}"; }问题是 :
为什么不从我的脚本调用GetPerson方法?我在GetPerson中附加调试器,但似乎没有调用.
任何帮助将不胜感激!
解决方法
WebMethods默认响应POST而不是GET请求.
@H_404_11@$.ajax({
type: 'POST',url: 'Default2.aspx/GetPerson',dataType: 'json',// ...
});
并且,请求格式也应该是JSON以匹配ResponseFormat:
@H_404_11@// ... data: JSON.stringify({ 'firstname': 'brian','lastname': 'lee' }),contentType: 'application/json'或者,可以将ScriptMethod配置为使用GET:
@H_404_11@[ScriptMethod(ResponseFormat = ResponseFormat.Json,UseHttpGet = true)]虽然,仍然需要为它设置contentType,所以不能使用$.getJSON():
@H_404_11@$.ajax({ type: 'GET',contentType: 'application/json',数据将进行URL编码,但在此之前,每个值都需要进行JSON编码: @H_404_11@// ... data: { firstname: JSON.stringify('brian'),lastname: JSON.stringify('lee') }另请注意,ScriptMethods会将其响应包装在{“d”:…}对象中.并且,由于返回值是一个String,“d”的值是同一个未解析的String:
@H_404_11@// ... success: function (response) { response = JSON.parse(response.d); alert(response.Age); }