简体   繁体   中英

exec function before every ajax success callback

I have a website where I rely on a lot of custom API call. My API return always an XML.

Currently, at the start of each and every $.get or $.post I call, I have this snippet :

var root = $($.parseXML(data)).find("Response");

if (root.children("Type").text() == "Error") {
  toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
  return;
}

However, I feel this code to be much redundant on one of my page, it's used 15 times.

I tried to use the $(document).ajaxSuccess() but the event.stopPropagation don't seem to work here

Is there a way to "intercept" each and every ajax call responses, do some stuff and possibly prevent the call to other defined success functions ?

I assume that you have something like this in many places in your code

$.ajax({
    method: "GET",
    url: "someurl.html",
    dataType: "xml",
    success : function() {
        var root = $($.parseXML(data)).find("Response");
        if (root.children("Type").text() == "Error") {
          toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
          return;
        }
        // ...
    },
    error : function(qXHR, textStatus, errorThrown){
        toastr.error(errorThrown, "Error " + qXHR.status);
    }
});

you could create a generic custom ajax function tha you can re-use

function baseAjaxCall(option, sCb) {    
    var ajaxOptions = {
        method: option.method || "GET",
        url: option.url,
        dataType: option.dataType || "xml",
        success : function(data) {
            var root = $($.parseXML(data)).find("Response");
            if (root.children("Type").text() == "Error") {
              toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
              return;
            }
            else {
                sCb(root);
            }
        },
        error : function(qXHR, textStatus, errorThrown){
            toastr.error(errorThrown, "Error " + qXHR.status);
        }
    };
    //you can check for optional settings
    if(option.contentType  !== undefined){
        ajaxOptions.contentType = option.contentType;
    }

    $.ajax(ajaxOptions);
}

everywhere in your code you can re-use the baseAjaxCall function

baseAjaxCall({ url: "someurl.html" }, function(root){
 // no need to chek for errors here!
});

Hope it's helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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