jQuery.getJSON调用ASP.NET方法

前端之家收集整理的这篇文章主要介绍了jQuery.getJSON调用ASP.NET方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有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')
    }

另请注意,ScriptMethods会将其响应包装在{“d”:…}对象中.并且,由于返回值是一个String,“d”的值是同一个未解析的String:

// ...
    success: function (response) {
        response = JSON.parse(response.d);
        alert(response.Age);
    }

猜你在找的Json相关文章