weixin_33720452 2013-05-10 06:24 采纳率: 0%
浏览 44

Django / Ajax获取请求

I'm trying to implement client/server communication using Django and Ajax and I'm having problem with Ajax request.

Here is my view:

from django.http import HttpResponse
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

from taskmanager.models import Task
from taskmanager.serializers import TaskSerializer


class JSONResponse(HttpResponse):

    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)


def task_list(request):
    if request.method == 'GET':
        tasks = Task.objects.all()
        serializer = TaskSerializer(tasks, many=True)
        return JSONResponse(serializer.data)

And my jquery code:

$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
            type: "get",
            url: "http://127.0.0.1:8000/",
            dataType: "json",
            success: function(data){
                alert(data[0]["title"]);
            },
            error: function(){
                alert("error");
            }
        });
    });
});

Every time server returns status 200 OK, but the error function is executed. When I visit that url directly in browser I get valid json output. Even more, if I put that output in a file and reference it in ajax call url it works as intended.

P.S. Sorry for my English.

UPDATE: Also, when I view response details in FireBug it has no response body.

Response headers:

Server:WSGIServer/0.1 Python/2.7.3
Date:Fri, 10 May 2013 07:56:23 GMT 
Content-Type:application/json

UPDATE: changed AJAX url to: "http://127.0.0.1:8000/?callback=?" and now I get response body: [{"id": "518a92147c2fce152b081878", "title": "New task"}, {"id": "518a905e7c2fce1516b8f9dc", "title": "Save the galaxy"}, {"id": "518a904e7c2fce1516b8f9da", "title": "Do a barrel roll"}], status -- 200 and error -- parsererror.

  • 写回答

2条回答 默认 最新

  • weixin_33726318 2013-05-10 07:44
    关注

    I think there is an error in your js Content negotietion

    instead of

    dataType: "json",
    

    use

    contentType: 'application/json',
    

    or try without this field

    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题