django + jQuery AJAX POST数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django + jQuery AJAX POST数据相关的知识,希望对你有一定的参考价值。
废话少说,直接代码伺候:
views:
from django.http import JsonResponse def test_post(request): name = request.POST[‘name‘] city = request.POST[‘city‘] qq = request.POST[‘qq‘] dict = {‘name‘:name,‘city‘:city,‘qq‘:qq} return JsonResponse(dict) def test(request): return render(request,‘app/accounts/test.html‘)
urls:
urlpatterns = [ url(r‘^test/$‘,views.test), url(r‘^test/post$‘,views.test_post,name=‘test_post‘), ]
test.html
{% load staticfiles %} <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>testajax</title> </head> <body> <div id="test"><h2>请点击下面的按钮,通过jQuery AJAX接收数据</h2></div> <div id="result"></div> <button id="btn1" type="button">获取服务器数据</button> <script src="{% static ‘jquery/jquery-2.2.0.min.js‘ %}"></script> <script src ="{% static ‘js/csrf.js‘ %}"></script> <script> $().ready(function(){ $(‘#btn1‘).click(function(){ $.post("{% url ‘test_post‘ %}", { csrfmiddlewaretoken:"{{ csrf_token }}", name:"dodo", city:"Ganzhou", qq:"12519460" }, function (data,status) { $.each(data,function(key,value){ $("#result").append(status +":"+key +":"+value +"<br/>") }) } ) }) }) </script> </body> </html>
关于POST数据:csrf_token报错问题,参照自强学堂http://www.ziqiangxuetang.com/django/django-csrf.html。同时把js/csrf.js代码如下:
/** * Created by dodo on 2016/1/29. */ jQuery(document).ajaxSend(function(event, xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != ‘‘) { var cookies = document.cookie.split(‘;‘); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + ‘=‘)) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function sameOrigin(url) { // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = ‘//‘ + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + ‘/‘) || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + ‘/‘) || // or any other URL that isn‘t scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } function safeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } if (!safeMethod(settings.type) && sameOrigin(settings.url)) { xhr.setRequestHeader("X-CSRFToken", getCookie(‘csrftoken‘)); } });
最后效果图:
以上是关于django + jQuery AJAX POST数据的主要内容,如果未能解决你的问题,请参考以下文章
python测试开发django-130.jQuery中$.ajax()方法发GET/POST/DELETE请求
jQuery AJAX POST 在第一次调用时跳过 Django CSRF 令牌标头
没有 jquery 的 Django CSRF 丢失或不正确的 Ajax POST (Vanilla JavaScript)
python测试开发django-131.jQuery中$.ajax()方法POST提交contentType:“application/json“类型数据