Ajax发送POST请求对数据的封装

Ajax发送POST请求把数据到后端后,后端收到数据并解析出来

示列一:

Ajax发送请求,这里主要是发送一个数组的数据类型到后端,如果没有先把数组进行格式化成字符串的话,后端就收了就是一个字符串类型,为了后端接收的是一个列表的类型,所以先进行JSON.stringify()进行数据的转化:

var tr = $(":checked").parent().parent();
    if(tr.length != 0){
        tr.each(function(){
            postList.push($(this).attr('id'));      // 选择的id
        });
        //console.log(postList);                       // [1,2,3]

        if(postList != ''){
            $.ajax({
            url: '/demo/user/',
            type: 'POST',
            dataType: 'JSON',
            // data: JSON.stringify(postList),       //这里是把列表转化为字符串
            data: JSON.stringify({                     // 把键值对格式转化为字符串
            'postList':postList,
            'value':status
            }),
            success:function (arg) {
               if(arg.status){
                    alert(arg.msg);
                    window.location.reload();
               }else {
                    alert(arg.msg);
               }
               }
            });
            }
        }else{
            alert('请选择要设置的用户')
        }

  

Py后端接收:

def users_list(request):
    if request.method == "POST":
        content = request.body                            # 字节
        content = str(content, encoding='utf-8')    # 字符串
        result = json.loads(content)                      # 再通过json解析成一个字典,字典包含前端传的列表
        # print('结果', result,type(result))              # {'value': 'True', 'postList': ['5']} <class 'dict'>
        response = {'status':False,'msg':None}
        # for id in result:
        for id in result['postList']:
             print(id)
        return JsonResponse(response)

示列二:

Ajax发送请求:

$.ajax({
                url: '/demo/user/',
                type: 'POST',
                dataType: 'JSON',
                // data: JSON.stringify(postList),       //这里是把列表转化为字符串
                data:{                     // 把键值对格式转化为字符串
                    'username':'ray',
                    'password':'123456'
                },
                success:function (arg) {
                    if(arg.status){
                        alert(arg.msg);
                        window.location.reload();
                    }else {
                        alert(arg.msg);
                    }
                }
            });

这里data也可以用FormData来封装数据,例如:
var data = new FormData();
data.append('name',$(":input[name='name']").val());
data.append('file',$(":input[name='file']")[0].files[0]);  //文件

  

Py后端接收:

def ajaxpost(request):
        result = {}
        if request.method == "POST":
        username = request.POST.get('username ')
        password= request.POST.get('password')
        return Jsonresponse(result)

  

总结:

这里主要是记录Ajax发送数据对数据格式的封装。

① 如果前端需要发送一个列表格式的数据给后端,则需要通过 JSON.stringify() 先把数据转换为字符串发送给后端,后端可以通过request.body获取到数据并把数据用 json.reloads 解析出来。

② 如果前端直接发送一个键值对的数据给后端,后端在接收数据的时候可直接通过request.POST获取即可。

原文地址:https://www.cnblogs.com/ray-h/p/10725048.html