我想从 javascript 调用网络服务.
I want to call a webservice from javascript.
这是我的代码:
var method="GetStock"; var url = "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 代码:
My ServiceGetStock.asmx code:
[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 www.mywebsite.ro/ServiceGetStock.asmx/GetStock 500(内部服务器错误)
POST www.mywebsite.ro/ServiceGetStock.asmx/GetStock 500 (Internal Server Error)
[更新]
我忘了提到我在项目的 webconfig(使用 webservice)中添加的,因为我收到错误:
I forgot to mention that I added in webconfig of project(with webservice) because I got the error:
XMLHttpRequest 无法加载 www.mywebsite.ro/ServiceGetStock.asmx/你好世界.请求的资源上不存在Access-Control-Allow-Origin"标头.因此不允许访问源 'localhost:11300'.
XMLHttpRequest cannot load www.mywebsite.ro/ServiceGetStock.asmx/HelloWorld. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' localhost:11300' is therefore not allowed access.
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> </customHeaders> </httpProtocol> 推荐答案好的.我发现了问题.创建 ASMX 文件时,您必须阅读所有注释行.要允许使用 ASP.NET AJAX 从脚本调用此 Web 服务,请取消注释以下行.
Ok guys. I found the problem. When an ASMX file is created, you must read all comments lines. To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
//[System.Web.Script.Services.ScriptService]所以 GetStock 函数是:
So the GetStock function is:
[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 = "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); }问题解决了!感谢大家的提示......
Problem solved! Thanks all for tips.......
更多推荐
从 Javascript 调用 ASMX Web 服务
发布评论