Ajax JSON响应不起作用,类型不是json

时间:2014-07-09 06:06:05

标签: ajax json django django-views

我的浏览器错误:

POST http://127.0.0.1:8000/tree/ajax/move-card/ 403 (FORBIDDEN)

Remote Address:127.0.0.1:8000
Request URL:http://127.0.0.1:8000/tree/ajax/move-card/
Request Method:POST
Status Code:403 FORBIDDEN
Request Headersview source
Accept:
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fa;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:33
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:127.0.0.1:8000
Origin:http://127.0.0.1:8000
Pragma:no-cache
Referer:http://127.0.0.1:8000/tree/bored/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
id_card:3
id_status:2
position:-1
Response Headersview source
Content-Type:text/html
Date:Wed, 09 Jul 2014 06:00:34 GMT
Server:WSGIServer/0.1 Python/2.7.5
X-Frame-Options:SAMEORIGIN

在js:


$.ajax({
        url: "/tree/ajax/move-card/",
        type: "POST",
        data: {
            'id_card': id_card,
            'id_status': id_status,
            'position': position
        },
        success: function (data) {
            console.log(data)
        },
        error: function () {
            alert('کار نمی کنه');
        }
    });

在视图中:


def move_card(request):
    response_data = {'success': 'True'}
    return HttpResponse(json.dumps(response_data ), content_type="application/json")

1 个答案:

答案 0 :(得分:1)

csrf_exempt装饰器添加到move_card功能或将csrfmiddlewaretoken添加到a​​jax请求数据。

看看这个:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

示例代码:

将csrf_exempt添加到功能

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def move_card(request):
    response_data = {'success': 'True'}
    return HttpResponse(json.dumps(response_data ), content_type="application/json")

添加csrfmiddlewaretoken以发布数据

检查一下:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax