代码之家  ›  专栏  ›  技术社区  ›  Cody

如何将附加参数传递给jQuery$。ajax()函数

  •  -1
  • Cody  · 技术社区  · 7 年前

    我使用以下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);
                },
    
    
            });
        })
    
    }
    

    processData contentType .如何通过 处理数据 内容类型 对于这种情况?

    2 回复  |  直到 7 年前
        1
  •  3
  •   charlietfl    7 年前

    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 返回a 承诺如此使用 new Promise 是一种反模式。看见 What is the explicit promise construction antipattern and how do I avoid it?

        2
  •  1
  •   DarioDF    7 年前

    我不确定我是否正确,如果你想添加和覆盖对象的设置,你可以使用$.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));
        })
    
    }
    

    ajaxHanler(“url”,“data”,{contentType:“text/plain”});