我在
处获得了这个简单的webmethod示例http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
现场演示在网站上运行。我下载了示例代码并将代码复制到我的测试webapp中,如下所示 - 除了我的示例应用程序无法正常工作。我在我的(VS2013)示例应用程序的Scripts文件夹中有相同的jquery-1.3.2.min.js(我在这个文件夹中有几个jquery脚本)。
这是我的示例应用程序中的客户端脚本/标记代码(WebForm3是起始页)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>WebForm3</title>
<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "WebForm3.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick = "ShowCurrentTime()" />
</div>
</form>
</body>
</html>
这里是后面的代码 - 运行页面时没有错误 - 只是警报没有显示 - 我是否错误地引用了ajax中的url?
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
}
答案 0 :(得分:0)
<script type = "text/javascript">
function ShowCurrentTime() {
var userName = $('#txtUserName').val()
$.ajax({
type: 'POST',
url: 'WebForm3.aspx/GetCurrentTime',
data: JSON.stringify({ name: userName }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
Hi Rich,从我可以看到你的ajax调用大多是正确的但是你想确保你避免使用字符串连接传入参数,你可以通过使用数据哈希(即JSON.stringify)来做同样的事情)或传入您创建的变量以保存参数的数据。如果此修复无效,我建议创建一个变量并从txtUserName.ClientID加载值,我不能肯定地说,但这可能是另一个潜在的问题。希望这有帮助!