2013-11-25 96 views
5

我有jQuery代码来从服务器获取JSON:jQuery.getJSON呼叫ASP.NET方法

$(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,但似乎没有调用。

任何帮助将不胜感激!

+0

我不知道如果是这样的原因,你可以给属性名作为数据。 data:{'firstname':'brian','lastname':'lee'} –

+0

不,它不起作用 –

+0

http://stackoverflow.com/questions/16910982/calling-webmethod-returning-ilistt-from- jQuery的阿贾克斯与 - NHibernate的和-MVC。我想你需要摆脱webmethod.as每个这篇文章,webmethods已过时 –

回答

5

WebMethod s默认回应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') 
    } 

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

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

你说'默认情况下,WebMethods响应POST而不是GET请求。 。那么我如何设置WebMethod对GET做出回应? –

+0

@IswantoSan尽管有一些注意事项,但这是可能的。看我的编辑。 –

+0

非常感谢! –