2012-02-01 38 views
1

使用我有的一本書中的例子,我能夠使用jQuery的$ .ajax成功地向ASP.NET webform發出AJAX請求。不過,我還沒有成功使用$ .getJSON,$ .get或$ .post。是否可以使用$ .getJSON(或其他兩個)來創建一個網頁表單的AJAX請求?如果是這樣,你能舉一個例子嗎?我用於$ .ajax的示例涉及在用WebMethod屬性標記的代碼隱藏文件中使用靜態方法。

下面是一些示例客戶端的代碼,我使用的作品$阿賈克斯:

<script type="text/javascript"> 
    $(document).ready(function() { 

     $("#Button4").click(function() { 
      $.ajax({ type: "POST", dataType: "json", contentType: "application/json", url: "HelloWorld.aspx/GetInfo", data: "{}", success: function (result) { 
       alert(result.d); 
      }, error: function() { alert("error occurred"); } 
      }); 
     }); 
    }); 
</script> 
<input id="Button4" type="button" value="Get Info" /> 

這裏是後臺代碼:

public partial class HellowWorld : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
    } 

    [System.Web.Services.WebMethod] 
    public static string GetInfo() 
    { 
     return "hello world"; 
    } 
} 

一件事,可能需要了解的是當我使用$ .ajax時,響應標頭內容類型看起來是application/json。當我使用$ .getJSON時,它是text/html。這讓我覺得我錯過了將序列化轉換爲JSON的步驟。

這裏的樣品呼叫我是想,沒有工作:

$.getJSON("UpdatePanel.aspx/GetInfo", "{}", function (result) { alert(result.d); }); 
+1

我建議讓Firebug或使用Chrome開發人員的工具來監控網絡請求和響應。 jQuery ajax請求非常優雅地失敗,因此查看服務器響應是什麼很有用,即使jQuery將它放棄爲無效。 – Shad 2012-02-01 00:13:51

回答

0

請發表您的$.ajax代碼。 $.get()$.post()只是$.ajax()函數的簡短形式,所以您很可能會忽略那些必需的信息,並且您沒有意識到它包含在$.ajax()調用中。