python django怎么读_django/python在读json?

本文介绍了如何在Django中读取和返回JSON数据。通过示例代码展示了如何在视图中构建JSON数据,并使用HttpResponse返回,以及如何在HTML模板中利用jQuery进行AJAX请求来读取这些数据。
摘要由CSDN通过智能技术生成

Django是最容易读取的def sendJson(request):

if request.method == 'GET':

context = {"name":"Json Sample Data"}

return render_to_response('name.html',context)

Django模板Html代码

^{pr2}$

现在根据你的:def sendJson(request):

if request.method == 'GET':

jsonData = {

region: {

span: {

latitude_delta: 0.08762885999999526,

longitude_delta: 0.044015180000002374

},

center: {

latitude: 37.760948299999995,

longitude: -122.4174594

}

}

}

data = json.dumps(jsonData)

return HttpResponse(data, content_type="application/json")

您也可以使用jquery读取这些数据

另一个创建json并读取html的示例

在网址.py在url(r'^anotherexample/$', 'views.anotherexample', name="anotherexample"),

在视图.py在def anotherexample(request):

if request.method == 'POST':

_date = strftime("%c")

response_data = {}

response_data['status'] = 'taken'

response_data['issueTakenTime'] = _date

return HttpResponse(json.dumps(response_data), content_type="application/json")

Html视图和jquery$.ajax({

url: "/anotherexample/",

// contentType: "application/json; charset=UTF-8",

data: { csrfmiddlewaretoken: "{{ csrf_token }}", // < here

status : "taken"

},

type: "POST",

error: function(res) {

console.log("errr", res)

},

success: function(res) {

console.log("res", res)}

})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值