如何使用django和jquery ajax获取json?得到500内部服务器错误

时间:2013-08-03 23:09:17

标签: jquery python django

我正试图动态显示某个对象的详细信息,从sqlite3数据库中获取它们。我的代码基于教程,一切都完全相同,但我的页面上出现了500内部服务器错误(但教程运行完美)。

我安装了python 3.3和django 1.6。

这是我的代码:

url.py:

url(r'^cargar-inmueble/(?P<id>\d+)$', 'inmobiliaria.views.cargar_inmueble', name='cargar_inmueble_view'),

views.py:

import json
from django.http import HttpResponse, Http404
from inmobiliaria.models import *

....

def cargar_inmueble(request, id):
    if request.is_ajax():
        inmueble = Inmueble.objects.get(id=id)
        return HttpResponse( json.dumps({'nombre': inmueble.nombre,
        'descripcion': inmueble.descripcion, 'foto' : inmueble.foto }),
        content_type='application/json; charset=utf8')
    else:
        raise Http404

hover.js(这是主要的js脚本,必须重命名)

$(document).on("ready", inicio );

function inicio() {

    ...

    $("#slider ul li.inmueble").on("click", "a", cargar_inmueble);
}

function cargar_inmueble(data) {

    var id = $(data.currentTarget).data('id');

    $.get('cargar-inmueble/' + id, ver_inmueble);

}

查看chrome dev工具的控制台,每次我点击调用“cargar_inmueble”的链接时,我得到这个error并且“ver_inmueble”永远不会被调用..这是我的第一个使用python的网站所以我很丢失!

1 个答案:

答案 0 :(得分:0)

检查chrome dev工具的网络选项卡,然后您就会知道问题的根源。

另一种调试方法是简化您的视图:

def cargar_inmueble(request, id):
    inmueble = Inmueble.objects.get(id=id)
    return HttpResponse( json.dumps({'nombre': inmueble.nombre,
        'descripcion': inmueble.descripcion, 'foto' : inmueble.foto }),
        content_type='application/json; charset=utf8')

然后直接转到http://localhost:8000/cargar-inmueble/1,如果您将DEBUG=True留在settings.py,您就会看到堆栈跟踪。

此行最有可能导致错误:

inmueble = Inmueble.objects.get(id=id)

id不存在时,它会抛出DoesNotExist异常,你应该抓住它。另外我相信返回的JSON与你正在做的有点不同:

def cargar_inmueble(request, id):
    try:
        inmueble = Inmueble.objects.get(id=id)
    except Inmueble.DoesNotExist: # catch the exception
        inmueble = None

    if inmueble:
        json_resp = json.dumps({
            'nombre': inmueble.nombre,
            'descripcion': inmueble.descripcion, 
            'foto' : inmueble.foto 
        })
    else:
       json_resp = 'null'

    return HttpResponse(json_resp, mimetype='application/json')

当然,您可以使用get_object_or_404来获得更简单的代码。我只想展示基本想法。

希望它有所帮助。