我在单个 Visual Studio 解决方案中有两个简单的项目,以了解 ajax 请求的工作原理。一个是 Web 服务,第二个是使用 Web 服务的项目。以下是相关的代码片段。
Web 服务 #1st 项目
自定义类。
public class JSONResponse
{
public string message{ get; set; }
public JSONResponse()
{
message = string.Empty;
}
}
public class returnData
{
public string UserValue { get; set; }
public returnData()
{
UserValue = string.Empty;
}
}
网络方法
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public JSONResponse returnData(returnData objEnter)
{
JSONResponse jsObj = new JSONResponse();
jsObj.message = objEnter.UserValue;
return jsObj;
}
}
消费应用程序 #2nd 项目
Javascript对象创建
$(document).ready(function () {
$("#btnSubmit").click(function () {
debugger;
var objEnter = {
UserValue: $("#txtMsg").val()
}
pushToServer(objEnter, "returnData", "objEnter");
// pushToServer(object,function to call,name of the object);
});
});
AJAX 请求
function pushToServer(dataToPass, functionToCall, jsonObjectName) {
debugger;
$.ajax({
url: "http://localhost:12016/DisplayError.asmx/" + functionToCall,
type: "POST",
dataType: "json",
data: "{" + jsonObjectName + ":" + JSON.stringify(dataToPass) + "}",
timeout: 30000,
//async: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
return data;
alert(data);
},
error: function (result) {
//alert(e);
alert(result.status + ' ' + result.statusText);
}
});
}
但是在通过提琴手检查时,我得到以下HTTP 500 Error。
[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/returnData'.]
System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +546417
System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +212
System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47
System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +203
System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +128
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Chrome 控制台出现以下错误,
XMLHttpRequest cannot load http://localhost:12016/DisplayError.asmx/returnData. Origin http://localhost:12196 is not allowed by Access-Control-Allow-Origin.
Web 服务在端口 12016 上运行,项目在端口 12196 上。
我无法理解导致错误的原因。