javascript中的值如何传递到django下的views.py中或者数据库中?

AjaxAjax有很多种写法,包括JQueryJS,这里贴一个用JQuery写的最通用的AjaxPOST方法传递JSON格式数据:

$.ajax({
    url: "your url",    
    data: JSON.stringify({    // JSON格式封装数据
        name: xxx, 
        age: xx
    }),
    contentType: 'application/json',
    type: "POST",
    traditional: true,    // 需要传递列表、字典时加上这句
    success: function(result) { 
    }
    fail: function(result) {
    }
});

然后view.py里接收以上数据时,由于这里我用了JSON格式传递,因此需要反序列化:

# coding=utf-8
import json

def func(request):
    json_receive = json.loads(request.body)
    name = json_receive['name']
    age = json_receive['age']
    ...

如果不想在JS里转换格式,直接传递的话,view.py中这么写:

 
# coding=utf-8

def func(request):
    # 如果Ajax使用了GET方法,把下面的POST换成GET即可
    name = request.POST['name']
    age = request.POST['age']
    ...


all above has not be confired


原文地址:https://www.cnblogs.com/fengff/p/8073866.html