Calling ASMX Web Service from Javascript

前端 未结 2 1947
青春惊慌失措
青春惊慌失措 2020-12-10 15:21

I want to call a webservice from javascript.

This is my code:

    var method=\"GetStock\";
    var url = \"http://www.mywebsite.ro/ServiceGetStock.as         


        
相关标签:
2条回答
  • 2020-12-10 15:35

    use dataType: "jsonp", instead of dataType: "json", jsonp is for cross domian webservice. hope it will help.

    0 讨论(0)
  • 2020-12-10 15:41

    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]
    

    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;
            }
        }
    

    and the Ajax code is:

       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);
        }
    

    Problem solved! Thanks all for tips.......

    0 讨论(0)
提交回复
热议问题