为什么 Web 服务调用失败?在单击按钮时,使用 jquery 从 asp.net 页面调用 Web 服务。Web 服务返回一个 JSON 字符串:{"Message":"Hello World"}
. 我现在不想对返回的消息做任何事情。我只是试图调用 Web 服务而不会通过错误函数。请参阅下面的代码:
The Web service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Runtime.Serialization.Json;
namespace EForm.Services
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class PeopleWebService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
JavaScriptSerializer js = new JavaScriptSerializer();
var jsonData = new
{
Message = "Hello World"
};
string retJSON = js.Serialize(jsonData);
Context.Response.Write(retJSON);
}
}
}
The asp.net page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.7-vsdoc.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
<script type="text/javascript">
function getUserName() {
$.ajax({
url: "http://localhost:1211/Services/PeopleWebService.asmx/HelloWorld",
cache: false, // don't cache results
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function () {
alert("worked");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Status: " + xhr.status);
alert("Response Text: " + xhr.responseText);
alert("Thrown Error: " + thrownError);
}
});
return false;
}
$(document).ready(function () {
$("#Search").click(getUserName);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Search" runat="server" Text="Search" />
</form>
</body>
</html>
The Return Errors
FireFox 24.0
Status: 0
Response Text:
Thrown Error:
Opera 17.0
Status: 0
Response Text:
Thrown Error:
Chrome 30.0.1599.69 m
Status: 0
Response Text:
Thrown Error:
IE 10
Status: 200
Response Text: {"Message":"Hello World"}{"d":null}
Thrown Error: SyntaxError: Syntax error