从Javascript调用ASMX Web服务

我想从javascript调用web服务。

这是我的代码:

var method="GetStock"; var url = "http://www.mywebsite.ro/ServiceGetStock.asmx"; $.ajax({ type: "POST", url: url + "/GetStock", data: "{variant_id='1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccessCall, error: OnErrorCall }); function OnSuccessCall(response) { alert(response.d); } function OnErrorCall(response) { alert(response.status + " " + response.statusText); } 

我的ServiceGetStock.asmx代码:

  [WebMethod] public string GetStock(int variant_id) { try { ProductVariant variant = ProductVariantManager.GetProductVariantByID(variant_id); return variant.Stock.ToString(); } catch (Exception ex) { return ex.Message; } } 

我收到了错误消息:

POST http://www.mywebsite.ro/ServiceGetStock.asmx/GetStock 500(内部服务器错误)

[UPDATE]

我忘了提到我在项目的webconfig中添加了(使用webservice),因为我收到了错误:

XMLHttpRequest无法加载http://www.mywebsite.ro/ServiceGetStock.asmx/HelloWorld 。 请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此不允许Origin’http:// localhost:11300’访问。

        

好,朋友们。 我发现了问题。 创建ASMX文件时,必须读取所有注释行。 要允许使用ASP.NET AJAX从脚本调用此Web Service,请取消注释以下行。

  //[System.Web.Script.Services.ScriptService] 

所以GetStockfunction是:

  [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string GetStock(string variant_id) { SendEmail.SendErrorMail("in"+ variant_id); try { ProductVariant variant = ProductVariantManager.GetProductVariantByID(Convert.ToInt32(variant_id)); return variant.Stock.ToString(); } catch (Exception ex) { return ex.Message; } } 

和Ajax代码是:

  var url = "http://www.mywebsite.ro/ServiceGetStock.asmx"; $.ajax({ type: "POST", url: url + "/GetStock", data: "{variant_id:'1'}", contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccessCall, error: OnErrorCall }); function OnSuccessCall(response) { alert(response.d); } function OnErrorCall(response) { alert(response.status + " " + response.statusText); } 

问题解决了! 谢谢大家的提示…….

使用dataType:“jsonp”,而不是dataType:“json”,jsonp用于交叉domian webservice。 希望它会有所帮助。