处理URL查询(Django& JSON)

时间:2014-12-22 15:35:21

标签: python json django url

我希望网页返回基于URL查询的JSON。我怎么能这样做?

我安装了Django(显然是python)的服务器。

任何答案都将不胜感激。谢谢!

-CJ

1 个答案:

答案 0 :(得分:2)

您希望使用json.dumps()来帮助您将字典转换为json以及在HttpResponse中使用django.http。 一个粗略的例子可能是:

views.py:

import json
from django.http import HttpResponse

def get_mydata(request):
    response = dict()
    response['status'] = 'success'
    response['msg'] = 'hello, CJ'
    .... # more key-value pair as you need
    return HttpResponse(json.dumps(response), content_type="application/json")

urls.py:

from django.conf.urls import patterns
from django.conf.urls import url
import views

urlpatterns = patterns('',
    url(r'^get_data/', views.get_mydata, name='get_mydata')
)

HTML / JavaScript的:

$.ajax({
    "type": "GET",
    "dataType": "json",
    "url": "/get_data/",
    "success": function(result) {
        console.log(result); // here you get the json response from get_mydata() in views.py
    }
})