2013-11-25 94 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

非常感謝! –