废话少说,直接代码伺候:
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‘)); } });
最后效果图:
时间: 2024-10-26 10:01:37