ajax.post封装,Ajax发送POST请求对数据的封装

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‘]}

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值