Front-end jquery uses Ajax in several ways:
$.ajax using :
$.ajax ({URL:'/test_ajax', #发送url data:{a:1B:2, Csrfmiddlewaretoken:'{{Csrf_token}}'}, #post方式在Django中需要使用令牌防止跨站请求伪造 type:"Post", #请求方式, GET, post ... DataType:"text", #返回的数据类型, Text,json, XML success:function (data) {#成功返回后调用的回调函数 alert (data) } })
$.post using :
$.post ( '/test_ajax', #url {A:1, B:2 , Csrfmiddlewaretoken:'{{csrf_token}'}, #令牌 function (data) {# callback function on Success alert (data) } ,'text' #设置返回的数类型 )
JQuery 1.12 Jquery.post supports the object parameters, the specific parameters can refer to $.ajax (): Now some versions do not apply
$.post ({ URL:'/test_ajax', data:{a:1, B: 2, Csrfmiddlewaretoken:'{{csrf_token}'}, dataType:' text", success:function (data) { alert (data) } })
$.get use : (same post, no tokens required)
$. Get ( '/test_ajax', {A:1, B:2}, function (data) { alert (data) }, 'text' )
Add:
$.getscript: Instant Load---> loading and executing a JavaScript file via an HTTP GET request.
Before the JQuery 1.2 version, GetScript can only invoke the same domain JS file. 1.2, you can call JavaScript files across domains. Note: Safari 2 or earlier cannot execute scripts synchronously in the global scope. If you join the script through GetScript, add the delay function.
HTML code:
<input type="button" value="getscript" onclick= " func (); "/><input type="button" value="say" onclick="Say (); "/>
JavaScript code:
function func () { $.getscript ("/static/test.js", Function () {# The first parameter is the loaded file, the second is the callback function after the successful load of alert ("OK")} ) }
Test.js file:
function Say () { alert ("hello")}
Click the Getscript button to load the file, then click Say to execute the function in Test.js
$.getjson using :
Html:
<input type="button" value="getjson" onclick= " Func_json (); "/>
Script
function Func_json () { $.getjson ("/get_json", function ( Data) {#请求url (can also be loaded directly into the JSON static resource file), and the successful load callback function alert (data.username) }) }
Background:
URL (r"^get_json", Views.get_json) def Get_json (req): = {" Username":"lsda","Age":12 } = json.dumps (data) return httpresponse (data)
See more: http://jquery.cuishifeng.cn/jQuery.Ajax.html official website
jquery uses Ajax