如何使用$ .getJSON向ASP.NET webform发出AJAX请求?

问题描述:

使用我有的一本书中的例子,我能够使用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

请发表您的$.ajax代码。 $.get()$.post()只是$.ajax()函数的简短形式,所以您很可能会忽略那些必需的信息,并且您没有意识到它包含在$.ajax()调用中。