简体   繁体   English

在 asp.net 中没有在 AJAX 调用上达到成功事件

[英]Not hitting success event on AJAX call In asp.net

I am trying to bind Drop down from services.我正在尝试从服务绑定下拉。 But success event is not hitting.但是成功事件没有命中。

Science I have total 5000 records so in科学 我总共有 5000 条记录,所以在

web.config file I have added Binding May be due to this region I am getting "Internal server Error" ?我添加了绑定的web.config文件可能是由于这个区域我收到“内部服务器错误”? I am not sure about this Please guide me where I am doing wrong我不确定这个请指导我哪里做错了

AJAX AJAX

var AllProduct = [];
        function GetAllProduct() {
            var params = { DivisionCode: $('#ddlDivision').val() };
            $.ajax({
                type: 'GET',
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(params),
                url: 'Header.aspx/GetProduct',
                dataType: 'json',
                async: false,
                success: function (res) {
                    Product(res.d)
                    OnSuccessProductCall();

                }
            });
            function Product(pdata) {
                AllProduct = pdata;
            }
        }
        function OnSuccessProductCall(data, status) {
            result = AllProduct;
            $("[id$='ddlProduct']").append($("<option>").val("0").text("Select"));
            if (result != undefined && result.length > 0) {
                for (i = 0; i < result.length; i++) {
                    $("[id$='ddlProduct']").append($("<option>").val($.trim(result[i].BU_CAT_CODE)).text($.trim(result[i].BU_CAT_DESC)));
                }
            }
        }

Services服务

While debugging I can see my services returning Collection of data But not able to hit Success Event在调试时,我可以看到我的服务返回数据集合但无法点击成功事件

 [WebMethod]
        public static ServiceReference1.PRODUCT[] GetProduct(string DivisionCode)
        {
            ServiceReference1.MasterDataServiceClient oClient = new ServiceReference1.MasterDataServiceClient();
            ServiceReference1.PRODUCT[] prod = oClient.GetProducts(DivisionCode, null, null, null, null, null, null, null);
            return prod;
        }

Web.Cofig网络配置文件

<system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="basicHttp" allowCookies="true"
             maxReceivedMessageSize="20000000"
             maxBufferPoolSize="20000000">
          <readerQuotas maxDepth="32"
               maxArrayLength="200000000"
               maxStringContentLength="200000000"/>
        </binding>
        <binding name="WSHttpBinding_IMasterDataService" />
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://almhosrwfebpm01.almaraigroup.local:8524/AlmaraiDataService.svc" binding="wsHttpBinding" bindingConfiguration="basicHttp" contract="ServiceReference1.IMasterDataService" name="WSHttpBinding_IMasterDataService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>

My data type is JSON我的数据类型是JSON

Sample data Coming from Web Services.来自 Web 服务的示例数据。

在此处输入图片说明 Where I am doing wrong.我做错的地方。

Error Message错误信息

 {"Message":"An attempt was made to call the method \u0027GetProduct\u0027 using a POST request, which is not allowed.","StackTrace":"   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

在此处输入图片说明

Add this instead of [WebMethod]添加这个而不是[WebMethod]

[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
 public static ServiceReference1.PRODUCT[] GetProduct(string DivisionCode)
        {
            ServiceReference1.MasterDataServiceClient oClient = new ServiceReference1.MasterDataServiceClient();
            ServiceReference1.PRODUCT[] prod = oClient.GetProducts(DivisionCode, null, null, null, null, null, null, null);
            return prod;
        }

An attempt was made to call the method \'GetNextImage\' using a GET request, which is not allowed 尝试使用 GET 请求调用方法 \'GetNextImage\',这是不允许的

change the " data: JSON.stringify(params)," Try this:更改“数据:JSON.stringify(params)”,试试这个:

data: "{obj:" + JSON.stringify(params ) + "}",

In the web method: 1-change the return type to void.在 web 方法中: 1-将返回类型更改为 void。 2-Add this code : 2-添加此代码:

JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(prod));

this article should help: https://www.c-sharpcorner.com/blogs/how-to-retrieve-data-using-ajax-in-asp-net这篇文章应该会有所帮助: https : //www.c-sharpcorner.com/blogs/how-to-retrieve-data-using-ajax-in-asp-net

Well, Technically, you must always include an error event so you know when an ajax calls fails and handle it accordingly.好吧,从技术上讲,您必须始终包含一个error事件,以便您知道 ajax 调用何时失败并相应地处理它。 It is clearly a bad practice to ignore it.忽略它显然是一种不好的做法。

Secondly, as far as I know, a WebMethod doesn't allow a GET request, you must use a POST request so it responds back and sends the data without error, or if you strictly want to use WebMethod in a GET request then you should decorate your WebMethod with this attribute: [ScriptMethod (UseHttpGet = true)]其次,据我所知, WebMethod不允许GET请求,您必须使用POST请求,以便它无误地响应并发送数据,或者如果您严格想在GET请求中使用WebMethod ,那么您应该使用此属性装饰您的WebMethod[ScriptMethod (UseHttpGet = true)]

Here is the refined ajax call, Try this and see what error pops up and try to resolve it again.这是精炼的ajax调用,试试这个,看看会弹出什么错误,然后再次尝试解决它。

var AllProduct = [];
function GetAllProduct() {
    var params = { DivisionCode: $('#ddlDivision').val() };
    $.ajax({
            type: 'POST', // Modified this to a POST call
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(params),
            url: 'Header.aspx/GetProduct',
            dataType: 'json',
            async: false,
            success: function (res) {
                Product(res.d)
                OnSuccessProductCall();
            },
            error: function(err) { // Added this event to capture the failed requests.
                console.log(err);
            }
   }); 
   // ... Your Further Code ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM