【问题标题】:Tastypie ajax POST obj_create - How to return jsonTastypie ajax POST obj_create - 如何返回 json
【发布时间】:2012-03-29 20:16:30
【问题描述】:

我正在发送一个创建新用户的 POST,并且可以正常工作。

我的问题是如何将创建的用户的 pk 返回到 ajax 响应?

         $.ajax({
                url: 'http://localhost:8080/api/v1/create/user/',
                type: 'POST',
                contentType: 'application/json',
                data: '{"uuid": "12345"}',
                dataType: 'json',
                processData: false,
                success: function (r) {
                    console.log(r)
                },
            });

def obj_create(self, bundle, request=None, **kwargs):
        try:
            user = User.objects.create_user(bundle.data['uuid'],'1')
            user.save()


        except:
            pass
        return bundle

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    您可以在您的 UserResource 的 Meta 中设置 always_return_data=True,并且在 POST 和 PUT 请求中,它将返回创建的对象。

    来自docs

    always_return_data

    指定所有 HTTP 方法(DELETE 除外)应返回数据的序列化形式。默认为 False。

    如果为 False,则在 POST/PUT 上返回 HttpNoContent (204),其正文为空,以及请求完整资源的位置标头。

    如果为 True,则在 POST/PUT 上返回 HttpAccepted (202),其正文包含序列化形式的所有数据。

    【讨论】:

      【解决方案2】:

      每种资源都有脱水方法。您可以使用它向响应中添加任何数据。这是文档 - http://django-tastypie.readthedocs.org/en/latest/cookbook.html#adding-custom-values

      【讨论】:

        【解决方案3】:

        您可以使用 Location 标头(默认情况下由 Tastypie 设置),也可以尝试让 Tastypie 将新创建的实体发回。我相信第一个更简单。您还可以查看相关的 SO 问题:Is it ok by REST to return content after POST?

        首先你需要稍微修改一下 jQuery XHR 对象,

        // Required for reading Location header of POST responses.
        var _super = $.ajaxSettings.xhr;
        $.ajaxSetup({
            xhr: function () {
                var xhr = _super();
                var getAllResponseHeaders = xhr.getAllResponseHeaders;
                xhr.getAllResponseHeaders = function () {
                    var allHeaders = getAllResponseHeaders.call(xhr);
                    if (allHeaders) {
                        return allHeaders;
                    }
                    allHeaders = "";
                    $(["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma", "Location"]).each(function (i, header_name) {
                        if (xhr.getResponseHeader(header_name)) {
                            allHeaders += header_name + ": " + xhr.getResponseHeader(header_name) + "\n";
                        }
                    });
                    return allHeaders;
                };
                return xhr;
            }
        });
        

        这是必需的,因为 (after jQuery $.ajax docs):

        目前,由于 Firefox 中的一个错误,即 .getAllResponseHeaders() 虽然 .getResponseHeader('Content-Type') 返回一个非空字符串,但 .getAllResponseHeaders() 返回空字符串,因此不支持在 Firefox 中使用 jQuery 自动解码 JSON CORS 响应.

        可以通过覆盖 jQuery.ajaxSettings.xhr 来解决此问题,如下所示:

        然后就可以读取successCallback中的header了,像这样:

        successCallback: errorAwareCall(function (data, t, textStatus, XMLHttpRequest) {
            var loc = XMLHttpRequest.getAllResponseHeaders();
            var pk = parseInt(loc.match(/\/(\d+)(\/)*/)[1]);
            // Do something with the PK
        })
        

        【讨论】:

          猜你喜欢
          • 2013-11-24
          • 1970-01-01
          • 2012-10-06
          • 1970-01-01
          • 2012-04-21
          • 2011-11-01
          • 2011-02-06
          • 2012-04-25
          • 2018-07-14
          相关资源
          最近更新 更多