2017-08-07 79 views
0

我使用以下AJAX效用函数提出要求

function ajaxHandler(url, data) 
{ 
    return new Promise(function (resolve, reject) { 
     $.ajax({ 
      type: 'POST', 
      url: url, 
      dataType: 'json', 
      data: data, 
      success: function (data) { 
       resolve(data); 
      }, 
      error: function (xhr, textStatus, error) { 
       reject(error); 
      }, 


     }); 
    }) 

} 

默认设置的伟大工程的大部分时间,但也有相当多的情况下,在那里我想通过其他参数,如processDatacontentType。如何通过processDatacontentType这种情况?

+0

我在代码中看不到'processData'变量。另外'选项'不被使用。 – MaxZoom

+2

如此扩展一个对象, – epascarello

+1

你有一个'选项'对象,但你没有使用它? – axlj

回答

3

假设options是要传入的对象;将配置对象从功能移出是关于最干净的。然后使用$.extend更新默认

function ajaxHandler(url, data, options) { 

    var config = { 
    type: 'POST', 
    url: url, 
    dataType: 'json', 
    data: data 
    } 

    if (options && $.type(options) == 'object') { 
    $.extend(config, options); 
    } 

    return $.ajax(config)// add a global error handler if desired 
} 

用法:

ajaxHandler('path/to/server', {foo:'bar'), {type:'GET'}) 
    .then(function(data){ 
    console.log(data); 
    }).fail(function(){// or `catch` in jQuery version >=3 
    // handle error 
    }) 

注意$.ajax返回“thenable”所以使用new Promise承诺是一个反模式。请参阅What is the explicit promise construction antipattern and how do I avoid it?

+0

我们不需要在'.then()'之后的'ajaxHandler()'函数中发现错误吗? – Cody

+0

一切都取决于你想如何设置它......用全局错误处理程序或每次使用一个 – charlietfl

+0

非常感谢你 – Cody

0

我不知道如果我是正确的,如果你想添加和覆盖物的设置,您可以用$ .extend

function ajaxHandler(url, data, extraSettings) 
{ 
    return new Promise(function (resolve, reject) { 
     $.ajax($.extend({ 
      type: 'POST', 
      url: url, 
      dataType: 'json', 
      data: data, 
      success: function (data) { 
       resolve(data); 
      }, 
      error: function (xhr, textStatus, error) { 
       reject(error); 
      }, 


     }, extraSettings)); 
    }) 

} 

这样$ .extend(OBJ1,OBJ2)的回报obj1添加或覆盖obj2的属性。

你可以像这样使用它: ajaxHanler(“url”,“data”,{contentType:“text/plain”});