Django接收Json数据

本文演示了如何使用jQuery和Django处理JSON数据,并在后台解析和展示JSON对象的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

========================receivePost.html===========================================

<!DOCTYPE html>
<html>
<head>
    <title>This is html2</title>
    <script src="../static/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        //alert("Hello")
        $(function() {
            var json_obj = {
                userId:123,
                username: 'lushijie',
                datas: [
                    {
                        game_id: 1,
                        level: 'first'
                    },
                    {
                        game_id: 2,
                        level: 'second'
                    }
                ]
            }
            var json_str = JSON.stringify(json_obj);    //将JSON对象转变成JSON格式的字符串
            //$.post("http://127.0.0.1:8000/getPost",json_str, function(data){alert(data)}, "json");
            //alert(json_str)
            //$.post("http://django.com.cn:8000/receivePost", {'a' : json_str}, function(data){
            $.post("http://django.com.cn:8000/receivePost", json_str, function(data){
                    alert(data.userId)
                    alert(data.username)
                    alert(data.datas[0].game_id)
                    for(i in data){
                        alert(i+ data[i])
                    }
                }, "json");
            })
        //})


    </script>
</head>
<body>


</body>
</html>

================================View.py==============================================

import MySQLdb
from django.db import models
from app.models import Author
from django.http import HttpResponse
from django.http import HttpResponseRedirect
import json
import simplejson
from django.shortcuts import render_to_response


from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def receivePost(request):
    req={}
    if request.method=='POST':
        #a = request.POST.get('a', '')
        #req=simplejson.loads(a)
        req=simplejson.loads(request.body)
    return HttpResponse(simplejson.dumps(req))
def testPost(request):
    return render_to_response('receivePost.html')



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值