前端jquery使用ajax的几种方法:
$.ajax使用:
???$.ajax({ ???????????url:‘/test_ajax‘, #发送url ???????????data:{a:1,b:2,csrfmiddlewaretoken:‘{{ csrf_token }}‘}, #post方式在Django中需要使用令牌防止跨站请求伪造 ???????????type:"post", #请求方式,get, post... ???????????dataType:"text", #返回的数据类型,text,json, xml... ???????????success:function(data){ #成功返回后调用的回调函数 ???????????????alert(data) ???????????} ???????})
$.post使用:
???????$.post( ???????????‘/test_ajax‘, #url ???????????{a:1,b:2,csrfmiddlewaretoken:‘{{ csrf_token }}‘}, ?#令牌 ???????????function(data){ #成功时的回调函数 ???????????????alert(data) ???????????}, ???????????‘text‘ #设置返回的数类型 ???????)
jQuery 1.12 中 jQuery.post支持对象参数,具体的参数可以参考 $.ajax():现在某些版本并不适用
???????$.post({ ???????????url:‘/test_ajax‘, ???????????data:{a:1,b:2,csrfmiddlewaretoken:‘{{ csrf_token }}‘}, ???????????dataType:"text", ???????????success:function(data){ ???????????????alert(data) ???????????} ???????})
$.get使用:(同post,不需要令牌)
???$.get( ???????????‘/test_ajax‘, ???????????{a:1,b:2}, ???????????function(data){ ???????????????alert(data) ???????????}, ???????????‘text‘ ???????)
补充:
$.getScript:即时加载--->通过 HTTP GET 请求载入并执行一个 JavaScript 文件。
jQuery 1.2 版本之前,getScript 只能调用同域 JS 文件。 1.2中,您可以跨域调用 JavaScript 文件。注意:Safari 2 或更早的版本不能在全局作用域中同步执行脚本。如果通过 getScript 加入脚本,请加入延时函数。
html代码:
<input type="button" value="getscript" onclick="func();"/><input type="button" value="say" onclick="say();"/>
JavaScript代码:
???function func() { ???????$.getScript("/static/test.js",function () { #第一个参数为加载的文件,第二个为成功加载后回调函数 ???????????alert("ok") ???????}) ???}
test.js文件:
function say(){ ???alert("hello")}
先点击getscript按钮加载文件,再点击say可以执行test.js中的函数
$.getJSON使用:
html:
<input type="button" value="getjson" onclick="func_json();"/>
script:
???function func_json(){ ???????$.getJSON("/get_json",function (data) { #请求url(也可以直接载入json静态资源文件),和成功载入后的回调函数 ???????????alert(data.username) ???????}) ???}
后台:
url(r"^get_json",views.get_json)def get_json(req): ???data = {"username":"lsda","age":12} ???data = json.dumps(data) ???return HttpResponse(data)
更多请看:http://jquery.cuishifeng.cn/jQuery.Ajax.html官网
jquery使用ajax
原文地址:https://www.cnblogs.com/ssyfj/p/8658729.html