【发布时间】:2015-07-17 14:38:31
【问题描述】:
我无法从我的 Visual Studio 项目中的 html 页面获取简单的 ajax 示例。它可以在网络表单 (aspx) 中正常工作:
... webform1.aspx 和 form1.html ...
function ShowCurrentTime() {
alert("before json");
$.ajax({
type: "POST",
url: "json.aspx/GetCurrentTime",
data: "{name: bob }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
alert("after json");
}
function OnSuccess(response) {
alert(response.d);
}
... webform1.aspx 和 form1.html ...
<input id="btnGetTime" type="button" value="Show Current Time"
onclick="ShowCurrentTime()" />
... json.aspx ...
[WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
如果我将代码放在 webform1.aspx 中,它可以正常工作。如果我把它放在 form1.html 上,json.aspx 不会返回任何内容。我正在使用 vs2013 从我的机器上以调试模式运行项目。任何帮助将不胜感激。
更新 #1
我检查了提琴手,服务器返回以下结果(500):
{"Message":"Invalid JSON primitive: bob.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at ...
【问题讨论】:
-
form1.html 和 webform1.aspx 是否在同一目录下?
-
在浏览器中打开开发者工具并在 Javascript 控制台中查找任何错误
-
form1.html 是否加载 jquery.js?
-
是的,form1.html和webform1.aspx在同一个目录下。是的,jquery 已经加载,通过调用 if (window.jQuery) { // jQuery is loaded alert('jquery is loaded'); 来确认}
-
检查了Firefox浏览器控制台,按下按钮时控制台中没有任何错误。我只是得到之前/之后的警报。在 IE 中也试过。