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

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?