Dan*_*ana 37 asp.net ajax jquery
我正在做一些简单的测试(准备一个更大的项目)来使用JQuery AJAX调用ASP.NET WebMethod.在我的示例中,我的WebMethod返回一个简单的字符串.但是,当我尝试使用JQuery调用它时,我会返回整个HTML页面内容,而不仅仅是我的字符串.我错过了什么?
客户端 :
$(document).ready(function ready() {
$("#MyButton").click(function clicked(e) {
$.post("Default.aspx/TestMethod",
{name:"Bob"},
function(msg) {
alert("Data Recieved: " + msg);
},
"html"
);
});
});
Run Code Online (Sandbox Code Playgroud)
服务器端:
using System;
using System.Web.Services;
namespace JqueryAjaxText
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string TestMethod(string name)
{
return "The value submitted was " + name;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*rke 20
看看这个链接.我使用了他的一些其他帖子来成功调用WCF服务.请务必查看相关文章:
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
仔细阅读文章,但基本上:
$("#Result").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").text(msg.d);
}
});
});
Run Code Online (Sandbox Code Playgroud)
我想我对JQuery的$ .post命令中的"type"参数感到困惑.在与一些人交谈之后,似乎调用WebMethod的返回类型必须是"json".我试图使用"html".一旦我将其改为"json",然后一切正常.显然,用[WebMethod]修饰的方法只返回JSON,这就是我的挂机所在.
谢谢你们的回复.