【问题标题】:When saving a model, data in $.ajaxSetup is not merged保存模型时,$.ajaxSetup 中的数据不会合并
【发布时间】:2013-09-18 09:11:12
【问题描述】:

我有一个由 RESTful API 支持的 Ember.js 应用程序。会话控制是通过身份验证令牌完成的:一旦用户登录,他会将他的身份验证令牌附加到他向服务器发出的每个请求中。我通过向$.ajaxSetup 中的数据添加身份验证来做到这一点。

$.ajaxSetup({
  data: { auth_token: this.get('authToken') }
});

现在,这适用于 GET 请求。但是,当通过 POST 或 PUT 请求将模型保存到服务器时,Ember Data RESTAdapter 会将数据对象字符串化。在DS.RESTAdapter.ajax 中确实如此

....
if (hash.data && type !== 'GET') {
  hash.contentType = 'application/json; charset=utf-8';
  hash.data = JSON.stringify(hash.data);
}
...

因此,身份验证令牌不会合并到数据中。在this jQuery ticket 他们说这是他们永远不会支持的东西。

解决这个问题的最优雅的方法是什么?我宁愿不覆盖 Ember 的 RESTAdapter.ajax 函数,因为代码变化如此之快,所以我覆盖的函数可能与下一个版本的代码库的其余部分不兼容。

【问题讨论】:

    标签: ember.js ember-data


    【解决方案1】:

    最后,除了覆盖RESTAdapter.ajax,我找不到其他解决方案。我最终添加了三个参数:auth[token]auth[school]auth[name]

    DS.RESTAdapter.reopen({
      /* Override to add the authToken, school and name */
      ajax: function(url, type, hash) { 
        var adapter = this;
    
        return new Ember.RSVP.Promise(function(resolve, reject) { 
          hash = hash || {};
          hash.url = url;
          hash.type = type;
          hash.dataType = 'json';
          hash.context = adapter;
    
          if (hash.data && type !== 'GET') { 
            hash.contentType = 'application/json; charset=utf-8';
    
            /* Add the data to the hash before it's stringified. */
            if (HstryEd.Session.get('isLoggedIn')) { 
              hash.data.auth = {};
              hash.data.auth.token = HstryEd.Session.get('authToken');
              hash.data.auth.school = HstryEd.Session.get('currentUser').get('school');
              hash.data.auth.name = HstryEd.Session.get('currentUser').get('name');
            } 
    
            hash.data = JSON.stringify(hash.data);
          } 
    
          if (adapter.headers !== undefined) { 
            var headers = adapter.headers;
            hash.beforeSend = function (xhr) { 
              forEach.call(Ember.keys(headers), function(key) { 
                xhr.setRequestHeader(key, headers[key]);
              });
            };
          } 
    
          hash.success = function(json) { 
            Ember.run(null, resolve, json);
          };
    
          hash.error = function(jqXHR, textStatus, errorThrown) { 
            if (jqXHR) { 
              jqXHR.then = null;
            } 
    
            Ember.run(null, reject, jqXHR);
          };
    
          Ember.$.ajax(hash);
        });
      } 
    });
    

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      相关资源
      最近更新 更多