Django ajax方法提交表单,及后端接受数据

前台代码:

 {% block content %}
<div class="wrapper wrapper-content">
<div class="blog-content">
{% for blog in blog %}
<form id="formid" >
{% csrf_token %}
<div class="edit-title">
<b>标题</b>
<br>
<input name="id-blog" id="blog-id" type="hidden" value={{blog.id}}>
<input name="title" type="text" id="blog-title" value={{blog.title}}>
</div>
<div class="edit-content">
<b>正文</b>
<textarea name="body" id="blog-body">{{blog.body}}</textarea>
</div>
<div>
<!--<input type="submit" value="取消">-->
<button type="button" id="submit" >保存</button>
</div>
</form>
{% endfor %}
</div>

js代码:

 <!--ajax提交表单-->
<script type="text/javascript"> $(function(){
$('#submit').on('click', function(){
var id = $("#blog-id").val()
var title = $("#blog-title").val()
<!--var body = $("#blog-body").val()-->body是tinymce富文本编辑器,不能这样获取
var body= tinyMCE.getInstanceById('blog-body').getBody().innerHTML;//谷歌中可以获取到body,火狐获取不到 $.ajax({
cache: false,
type: "POST",
url:"/sub_article/",
data:{'title': title, 'body': body,'blogId':id},
dataType:"json",
async: true,
beforeSend:function(xhr, settings){
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
<!--回调函数success的data和上面的传如参数data不是一个-->
success: function(data) {
if(data.status == 'success'){
console.log(data)
alert("提交成功");
<!--window.location.reload();-->
}else {
alert("fail");
}
},
});
});
})
</script>

views:

 def sub_article(request):
# if request.is_ajax:
if request.method == 'POST':
# 获取ajax传过来的参数值
data = request.POST
id = data.get('blogId')
print 'id:%s' % id
title = data.get('title')
body = data.get('body')
# body = request.POST.get("blog-body")#此种方式不能获取到值
print "title:%s" % title
print "body:%s" % body
BlogPost.objects.filter(id=int(id)).update(title=title)
BlogPost.objects.filter(id=int(id)).update(body=body) # 更改数据
# BlogPost.objects.create(title=title)
# BlogPost.objects.create(body=body)#提交时插入两条半截数据很可能是这里分开执行引起的,需要通过id来准确定位修改哪条数据
return HttpResponse('{"status":"success"}', content_type='application/json')
else:
return HttpResponse('{"status":"fail", "msg":"fail hhahh"}', content_type='application/json')

接收参数

1.GET 方式 

$.ajax({ 
url:'/hello/getTest', 
type:'GET', 
data:{'a':3333,'b':444}, 
success:function(data){ 
alert(data.message); 

}) 

views->参数解析和用数据字典的方式返回json 数据(跨域名请求数据,则使用 jsonp字符串)

```
def getTest(request):
data = request.GET
print(data)
a = data.get('a')
b = data.get('b')
response_data = {}
response_data['result'] = 's'
response_data['message'] = a+b
return HttpResponse(json.dumps(response_data), content_type="application/json")
```
     function postTest() {
$.ajax({
url:'/hello/postTest',
type:'POST',
data:{'a':3333,'b':444},
success:function(data){
alert(data.message);
}
})
}

views-> 引入from django.views.decorators.csrf import csrf_exempt,并且增加注解@csrf_exempt,目的是避开CSRF检查

    @csrf_exempt
def postTest(request):
data = request.POST
print(data)
a = data.get('a')
b = data.get('b')
response_data = {}
response_data['result'] = 's'
response_data['message'] = a+b
return JsonResponse(response_data)

注意点:

  1. post 方式有避开CSRF检查,具体不回避CSRF检查的方式需要再研究
  2. 返回Json的方式有两种
<!--ajax提交表单-->
<script type="text/javascript"> $(function(){
$('#submit').on('click', function(){
var id = $("#blog-id").val()
var title = $("#blog-title").val()
<!--var body = $("#blog-body").val()-->body是tinymce富文本编辑器,不能这样获取
var body= tinyMCE.getInstanceById('blog-body').getBody().innerHTML;//谷歌中可以获取到 $.ajax({
cache: false,
type: "POST",
url:"/sub_article/",
data:{'title': title, 'body': body,'blogId':id},
dataType:"json",
async: true,
beforeSend:function(xhr, settings){
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
},
<!--回调函数success的data和上面的传如参数data不是一个-->
success: function(data) {
if(data.status == 'success'){
console.log(data)
alert("提交成功");
<!--window.location.reload();-->
}else {
alert("fail");
}
},
});
});
})
</script>
上一篇:使用ajax异步提交表单


下一篇:HAVING用法详解