Step1:
我将脚本定义为:home.aspx
页面上:
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
headers: { "Content-Type": "application/json" },
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
步骤2:
从按钮调用脚本函数:它在页面上home.aspx
:
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
步骤3:
在home.aspx.cs
页面上定义的 Web 方法:
[System.Web.Services.WebMethod]
public static string GetData(string name)
{
return "Welcome";
}
我得到:
JavaScript 运行时错误:无法获取未定义或 空引用
你必须把你的数据串起来:
data: JSON.stringify({ name: "Mobile" })
并像这样使用 ajax:
$.ajax({ ... });
完整脚本已更新:
function ShowCurrentTime() {
$.ajax({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: JSON.stringify({ name: "Mobile" }),
contentType: "application/json",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
试试这个并告诉我它是否有效:
<script type = "text/javascript">
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);},
failure: function() {
alert("Fail");}
});
}
</script>