基本上,我試圖將原始SQL查詢結果轉換爲JSON對象,然後通過AJAX將其發送到客戶端。 這是我的看法(我使用Django的1.8.6)通過AJAX將Django對象從Django視圖返回給客戶端
import MySQLdb
from django.db import connection
import json
from django.http import HttpResponse
from django.core import serializers
def test_view(request):
cursor = connection.cursor()
cursor.execute("select id, name from okved")
data = cursor.fetchall
json_data = serializers.serialize('json', data)
return HttpResponse(json_data, content_type="application/json")
相應的URL配置
url(r'^test/$', test_view),
jQuery函數
var test = function()
{
$.ajax({
type:"GET",
url:"/test",
dataType : 'json',
cache: "false",
data:{},
success:function(response)
{
alert("Test successful");
}
});
return true;
}
我經常收到GET http://127.0.0.1:8000/test/ 500 (內部服務器錯誤)錯誤,我遵循所有建議我在這裏遇到了前面的線索。我真的很感激任何幫助。我已經打消了我的想法嘗試在這上衝浪Stackoverflow。
你的問題是什麼?你有什麼錯誤?請修改您的問題以反映這些問題。 –
GET http://127.0.0.1:8000/test/ 500(內部服務器錯誤) –
我認爲'fetchall'是一個函數('fetchall()'),BTW,這個錯誤與JSON響應無關,你有如果可能的話,在您的視圖中出現邏輯錯誤,發佈完整的追溯。 – Gocht