首页 > Web开发 > 详细

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

时间:2019-04-17 18:07:12      阅读:347      评论:0      收藏:0      [点我收藏+]

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

示列一:

Ajax发送请求:

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(‘请选择要设置的用户‘)
        }

  

后端接收:

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]);  //文件

  

后端接收:

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获取即可。

 

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!