Less nonsense, direct code:
Views
fromDjango.httpImportJsonresponsedefTest_post (Request): Name= Request. post['name'] City= Request. post[' City'] QQ= Request. post['QQ'] Dict= {'name': Name,' City': City,'QQ': QQ}returnjsonresponse (dict)defTest (Request):returnRender (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>"ZH-CN">"UTF-8"> <title>testajax</title>"Test">"result"></div><button id="BTN1"Type="Button"> Get Server Data </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,val UE) {$ ("#result"). Append (Status +":"+key +":"+value +"<br/>") }) } ) }) })</script></body>About Post data:csrf_token error problem, referring to the self-improvement school http://www.ziqiangxuetang.com/django/django-csrf.html. Also put the Js/csrf.js code as follows:
/** * 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; } } } returnCookievalue; } function Sameorigin (URL) {URL could be relativeorScheme relativeorAbsolute VAR host= Document.location.host; Host +Port Var protocol=Document.location.protocol; var sr_origin='//'+host; var Origin= protocol +Sr_origin; Allow Absoluteorscheme relative URLs to same originreturn(url = = Origin | | Url.slice (0, origin.length + 1) = = Origin +'/') ||(URL= = Sr_origin | | Url.slice (0, sr_origin.length + 1) = = Sr_origin +'/') || //orAny 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')); }});
At last:
Django + jQuery AJAX post data