【问题标题】:jQuery.getJSON Call ASP.NET methodjQuery.getJSON 调用 ASP.NET 方法
【发布时间】:2013-11-25 05:10:33
【问题描述】:

我有 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 中附加了调试器,但似乎没有调用。

任何帮助将不胜感激!

【问题讨论】:

  • 我不确定这是否是原因,您可以将属性名称作为数据。数据:{ 'firstname': 'brian', 'lastname': 'lee' }
  • stackoverflow.com/questions/16910982/…。我想你需要摆脱 webmethod。根据这篇文章,webmethods 已经过时了
  • 我使用的是 ASP.NET,而不是 ASP MVC..:)

标签: jquery asp.net json


【解决方案1】:

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',
    url: 'Default2.aspx/GetPerson',
    dataType: 'json',
    contentType: 'application/json',
    // ...
});

并且,data 将进行 URL 编码,但在此之前每个值都需要进行 JSON 编码:

// ...
    data: {
        firstname: JSON.stringify('brian'),
        lastname: JSON.stringify('lee')
    }

还要注意ScriptMethods 会将他们的响应包装在{ "d": ... } 对象中。而且,由于return 的值是String,所以"d" 的值与未解析的String 相同:

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

【讨论】:

  • 你说WebMethods by default respond to POST rather than GET requests.。那么如何设置 WebMethod 响应 GET 呢?
  • @IswantoSan 这是可能的,但有一些警告。查看我的编辑。
猜你喜欢
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 2012-05-31
  • 1970-01-01
  • 2010-10-09
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多