python - django 使用 ajax 发送数组数据到后台并转换成列表

一。前端 ajax

var order_list = [1, 2, 3];

$.ajax({
    url: "/stores/order/",
    method: "POST",
    traditional: true,    // 加上此参数(序列化数据)
    data: {
        'order_list': JSON.stringify(order_list),
        'csrfmiddlewaretoken': $("[name='csrfmiddlewaretoken']").val(),
    },
    success: function (data) {
        console.log(data);
    }, error: function (data) {
        alert("请求错误!")
    }
})

二。后端

def order(request):
    order_list = request.POST.getlist("order_list")
    order_list = analysis_str_list(order_list)
    # 拿到数组后进行数据库操作
    for order_id in order_list:
        order_obj = Order.object.filter(id=order_id).first()
    
    # .....

def analysis_str_list(s):    
    """自定义解析列表的方法"""
    this_list = []
    li = s[0].replace("[", "").replace("]", "").split(",")
    for i in li:
        for j in i:
            try:
                int(j)
                this_list.append(int(j))
            except Exception as e:
                pass
    return this_list 

猜你喜欢

转载自www.cnblogs.com/chaoqi/p/11228418.html