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