2015-05-18 49 views
3

我有一个网站,我依靠很多自定义API调用。我的API返回总是一个XML。每个Ajax成功回调之前的exec函数

目前,在每次开始和每$不用彷徨或$。员额我打电话,我有这样的片段:

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

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

不过,我觉得这个代码是在我的页面的一个多少冗余,它使用了15次。

我试图使用的$(document).ajaxSuccess(),但event.stopPropagation似乎并不在这儿工作

有没有一种方法来“拦截”每一个Ajax调用的响应,做一些东西,并可能阻止对其他定义的成功函数的调用?

回答

2

我假设你有很多地方像这样在你的代码

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

,你可以在创建一个通用的自定义AJAX功能塔,你可以重新使用

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

任何一个地方代码你可以重新使用baseAjaxCall函数

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

希望它是帮助!