【发布时间】:2012-02-01 00:10:21
【问题描述】:
使用我所拥有的书中的一个示例,我能够使用 jQuery 的 $.ajax 成功地向 ASP.NET 网络表单发出 AJAX 请求。但是,我没有成功使用 $.getJSON、$.get 或 $.post。是否可以使用 $.getJSON(或其他两个)来发出网络表单的 AJAX 请求?如果是这样,你能举个例子吗?我用于 $.ajax 的示例涉及在代码隐藏文件中使用静态方法,该文件标记有 WebMethod 属性。
下面是一些使用 $.ajax 对我有用的示例客户端代码:
<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); });
【问题讨论】:
-
我建议使用 FireBug 之类的工具或使用 Chrome 的开发人员工具来监控网络请求和响应。 jQuery ajax 请求非常优雅地失败,因此查看服务器响应是很有用的,即使 jQuery 将其丢弃为无效。