jQuery.getJSON调用ASP.NET方法
发布时间:2020-12-16 18:40:52 所属栏目:百科 来源:网络整理
导读:我有jQuery代码从服务器获取 JSON: $(document).ready(function () { $.getJSON('Default2.aspx/GetPerson',{ 'firstname': 'brian','lastname': 'lee' },function (response) { alert(response.Age); }); }); Default2.aspx代码: [WebMethod] [ScriptMeth
我有jQuery代码从服务器获取
JSON:
$(document).ready(function () { $.getJSON('Default2.aspx/GetPerson',{ 'firstname': 'brian','lastname': 'lee' },function (response) { alert(response.Age); }); }); Default2.aspx代码: [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请求.
$.ajax({ type: 'POST',url: 'Default2.aspx/GetPerson',dataType: 'json',// ... }); 并且,请求格式也应该是JSON以匹配ResponseFormat: // ... data: JSON.stringify({ 'firstname': 'brian','lastname': 'lee' }),contentType: 'application/json' 或者,可以将ScriptMethod配置为使用GET: [ScriptMethod(ResponseFormat = ResponseFormat.Json,UseHttpGet = true)] 虽然,仍然需要为它设置contentType,所以不能使用$.getJSON(): $.ajax({ type: 'GET',contentType: 'application/json',数据将进行URL编码,但在此之前,每个值都需要进行JSON编码:// ... data: { firstname: JSON.stringify('brian'),lastname: JSON.stringify('lee') } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |