【问题标题】:Can not retrieve data from Django Rest Framework response, when use ajax使用 ajax 时无法从 Django Rest Framework 响应中检索数据
【发布时间】:2018-04-04 19:57:20
【问题描述】:

我正在尝试使用 jquery ajax 来使用我的 Django Rest API。我写一个简单的视图:

@api_view(["GET", "POST"])
@permission_classes((AllowAny,))
@method_decorator(csrf_exempt, name='dispatch')
def hello_world(request):
    if request.method == 'POST':
        return Response({"message": "Got some data!", "data": request.data})
    return Response({"message": "Hello, world!"})

以及消耗前端代码:

            $('#redirect').click(function(){
                var data = {key1: "value1"};
                console.log('redirect button clicked');
                $.ajax({
                    type: "POST",
                    url: "http://127.0.0.1:8000/test/",
                    "data": data,
                    dataType: "jsonp",
                    success: function(data){
                        console.log('success');
                        console.log(JSON.stringify(data));
                        },
                    failure: function(errMsg) {
                        console.log('failure');
                        console.log(errMsg);
                        }
                    });
                });

我在后端收到成功代码:

[24/Oct/2017 08:44:05] "GET /test/?callback=jQuery21100695833324387296_1508823842460&key1=value1&_=1508823842461 HTTP/1.1" 200 27
[24/Oct/2017 08:44:06] "GET /test/?callback=jQuery21100695833324387296_1508823842460&key1=value1&_=1508823842462 HTTP/1.1" 200 27

并且在前端什么也没有收到:

redirect button clicked (08:44:06:227 | null)
  at public_html/index.html:112
redirect button clicked (08:44:06:885 | null)
  at public_html/index.html:112

我知道我丢失了一些简单的东西,但找不到。请告诉我我的代码有什么问题。

UPD。更改前端代码:

            $('#redirect').click(function(){
                var data = {key1: "value1"};
                console.log('redirect button clicked');
                $.ajax({
                    method: "POST",
                    url: "http://127.0.0.1:8000/test/",
                    "data": data,
                    dataType: "jsonp",
                    success: function(data){
                        console.log('success');
                        console.log(JSON.stringify(data));
                        },
                    failure: function(errMsg) {
                        console.log('failure');
                        console.log(errMsg);
                        }
                    });
                });

还是有同样的问题。

UPD2。为 request.data 添加输出:

@api_view(["GET", "POST"])
@permission_classes((AllowAny,))
@method_decorator(csrf_exempt, name='dispatch')
def hello_world(request):
    print(request.data)
    if request.method == 'POST':
        return Response({"message": "Got some data!", "data": request.data})

接收:

<QueryDict: {}>
[24/Oct/2017 13:57:19] "GET /test/?callback=jQuery21109646247308520148_1508842562290&key1=value1&_=1508842562293 HTTP/1.1" 200 27
<QueryDict: {}>
[24/Oct/2017 13:57:20] "GET /test/?callback=jQuery21109646247308520148_1508842562290&key1=value1&_=1508842562294 HTTP/1.1" 200 27

UPD3。更改前端的ajax请求部分:

                $.ajax({
                    method: "POST",
                    url: "http://127.0.0.1:8000/test/",
                    "data": data,
                    dataType: "jsonp",
                    success: function(inp_data){
                        console.log('success');
                        console.log(JSON.stringify(inp_data));
                        alert(JSON.stringify(inp_data));
                        },
                    error: function(arg1, errMsg) {
                        console.log('failure');
                        console.log(errMsg);
                        }
                    });

进入前端输出:

failure (15:23:58:959 | null)
  at public_html/index.html:124
parsererror (15:23:58:961 | null)
  at public_html/index.html:125

UPD4:再次更改我的前端代码:

                $.ajax({
                    method: "POST",
                    url: "http://127.0.0.1:8000/test/",
                    "data": data,
                    success: function(inp_data){
                        console.log('success');
                        console.log(JSON.stringify(inp_data));
                        alert(JSON.stringify(inp_data));
                        },
                    error: function(xhr, errMsg) {
                        console.log('failure');
                        console.log(errMsg);
                         console.log(xhr.status + ": " + xhr.responseText);
                        }
                    });

现在我在后端有正确的请求:

 <QueryDict: {'key1': ['value1']}>
[24/Oct/2017 15:52:12] "POST /test/ HTTP/1.1" 200 53

但是前端还是有问题:

failure (16:00:25:706 | null)
  at public_html/index.html:123
error (16:00:25:708 | null)
  at public_html/index.html:124
0: undefined (16:00:25:710 | null)
  at public_html/index.html:125

【问题讨论】:

  • 与您的日志一样,您的 ajax 代码以某种方式向您的服务器发送了一个 get 请求,因此您必须相应地得到响应,即丢失数据。而不是类型 POST 我认为你应该使用方法: POST

标签: jquery ajax python-3.x rest django-rest-framework


【解决方案1】:

您应该在前端 ajax 代码中使用 method: "POST"。默认情况下,它正在发送 GET 请求,因此您不会得到预期的结果。详情请参考this

希望这会有所帮助。

【讨论】:

  • 我刚刚更改了我的前端代码,但前端输出和后端都没有任何变化。
  • 能否在视图中打印 request.data 并显示出来?
  • 我也没有在 jquery ajax api 文档中找到任何 failure 回调选项。虽然有error回调函数可用。
  • 我刚刚在第一篇文章的更新中添加了我的请求数据。我还将“失败”更改为“错误”-它返回 obj。
  • 什么是obj?我也对请求方法有疑问,因为根据您的日志,您的服务器正在接收 GET 请求。你能确认吗?另外前端最新更新的输出是什么?
猜你喜欢
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
  • 1970-01-01
  • 2018-03-24
  • 2014-09-28
  • 1970-01-01
相关资源
最近更新 更多