前台代码:
1 {% block content %} 2 <div class="wrapper wrapper-content"> 3 <div class="blog-content"> 4 {% for blog in blog %} 5 <form id="formid" > 6 {% csrf_token %} 7 <div class="edit-title"> 8 <b>标题</b> 9 <br> 10 <input name="id-blog" id="blog-id" type="hidden" value={{blog.id}}> 11 <input name="title" type="text" id="blog-title" value={{blog.title}}> 12 </div> 13 <div class="edit-content"> 14 <b>正文</b> 15 <textarea name="body" id="blog-body">{{blog.body}}</textarea> 16 </div> 17 <div> 18 <!--<input type="submit" value="取消">--> 19 <button type="button" id="submit" >保存</button> 20 </div> 21 </form> 22 {% endfor %} 23 </div>
js代码:
1 <!--ajax提交表单--> 2 <script type="text/javascript"> 3 4 $(function(){ 5 $('#submit').on('click', function(){ 6 var id = $("#blog-id").val() 7 var title = $("#blog-title").val() 8 <!--var body = $("#blog-body").val()-->body是tinymce富文本编辑器,不能这样获取 9 var body= tinyMCE.getInstanceById('blog-body').getBody().innerHTML;//谷歌中可以获取到body,火狐获取不到 10 11 $.ajax({ 12 cache: false, 13 type: "POST", 14 url:"/sub_article/", 15 data:{'title': title, 'body': body,'blogId':id}, 16 dataType:"json", 17 async: true, 18 beforeSend:function(xhr, settings){ 19 xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); 20 }, 21 <!--回调函数success的data和上面的传如参数data不是一个--> 22 success: function(data) { 23 if(data.status == 'success'){ 24 console.log(data) 25 alert("提交成功"); 26 <!--window.location.reload();--> 27 }else { 28 alert("fail"); 29 } 30 }, 31 }); 32 }); 33 }) 34 </script>
views:
1 def sub_article(request): 2 # if request.is_ajax: 3 if request.method == 'POST': 4 # 获取ajax传过来的参数值 5 data = request.POST 6 id = data.get('blogId') 7 print 'id:%s' % id 8 title = data.get('title') 9 body = data.get('body') 10 # body = request.POST.get("blog-body")#此种方式不能获取到值 11 print "title:%s" % title 12 print "body:%s" % body 13 BlogPost.objects.filter(id=int(id)).update(title=title) 14 BlogPost.objects.filter(id=int(id)).update(body=body) # 更改数据 15 # BlogPost.objects.create(title=title) 16 # BlogPost.objects.create(body=body)#提交时插入两条半截数据很可能是这里分开执行引起的,需要通过id来准确定位修改哪条数据 17 return HttpResponse('{"status":"success"}', content_type='application/json') 18 else: 19 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)
注意点:
- post 方式有避开CSRF检查,具体不回避CSRF检查的方式需要再研究
- 返回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>