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

    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝