从Javascript调用ASMX Web服务

POI*_*OIR 7 javascript asp.net jquery web-services asmx

我想从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);
    }
Run Code Online (Sandbox Code Playgroud)

我的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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我收到了错误消息:

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

[UPDATE]

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

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

  <httpProtocol>
          <customHeaders>
              <add name="Access-Control-Allow-Origin" value="*" />
              <add name="Access-Control-Allow-Headers" value="Content-Type" />
          </customHeaders>
  </httpProtocol>
Run Code Online (Sandbox Code Playgroud)

POI*_*OIR 13

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

 //[System.Web.Script.Services.ScriptService]
Run Code Online (Sandbox Code Playgroud)

所以GetStock功能是:

  [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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

和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);
    }
Run Code Online (Sandbox Code Playgroud)

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