JS實現(xiàn)的ajax和同源策略(實例講解)
一、回顧jQuery實現(xiàn)的ajax
首先說一下ajax的優(yōu)缺點
優(yōu)點:
AJAX使用Javascript技術向服務器發(fā)送異步請求;
AJAX無須刷新整個頁面;
因為服務器響應內容不再是整個頁面,而是頁面中的局部,所以AJAX性能高;
jquery 實現(xiàn)的ajax
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="{% static 'JS/jquery-3.1.1.js' %}"></script> </head> <body> <button class="send_Ajax">send_Ajax</button> <script> //$.ajax的兩種使用方式: //$.ajax(settings); //$.ajax(url,[settings]); $(".send_Ajax").click(function(){ $.ajax({ url:"/handle_Ajax/", type:"POST", data:{username:"Yuan",password:123}, success:function(data){ alert(data) }, //=================== error============ error: function (jqXHR, textStatus, err) { // jqXHR: jQuery增強的xhr // textStatus: 請求完成狀態(tài) // err: 底層通過throw拋出的異常對象,值與錯誤類型有關 console.log(arguments); }, //=================== complete============ complete: function (jqXHR, textStatus) { // jqXHR: jQuery增強的xhr // textStatus: 請求完成狀態(tài) success | error console.log('statusCode: %d, statusText: %s', jqXHR.status, jqXHR.statusText); console.log('textStatus: %s', textStatus); }, //=================== statusCode============ statusCode: { '403': function (jqXHR, textStatus, err) { console.log(arguments); //注意:后端模擬errror方式:HttpResponse.status_code=500 }, '400': function () { } } }) }) </script> </body> </html>
Views.py
import json,time def index(request): return render(request,"index.html") def handle_Ajax(request): username=request.POST.get("username") password=request.POST.get("password") print(username,password) time.sleep(10) return HttpResponse(json.dumps("Error Data!"))
$.ajax參數(shù)
請求參數(shù)
######################------------data---------################ data: 當前ajax請求要攜帶的數(shù)據(jù),是一個json的object對象,ajax方法就會默認地把它編碼成某種格式 (urlencoded:?a=1&b=2)發(fā)送給服務端;此外,ajax默認以get方式發(fā)送請求。 function testData() { $.ajax("/test",{ //此時的data是一個json形式的對象 data:{ a:1, b:2 } }); //?a=1&b=2 ######################------------processData---------################ processData:聲明當前的data數(shù)據(jù)是否進行轉碼或預處理,默認為true,即預處理;if為false, 那么對data:{a:1,b:2}會調用json對象的toString()方法,即{a:1,b:2}.toString() ,最后得到一個[object,Object]形式的結果。 ######################------------contentType---------################ contentType:默認值: "application/x-www-form-urlencoded"。發(fā)送信息至服務器時內容編碼類型。 用來指明當前請求的數(shù)據(jù)編碼格式;urlencoded:?a=1&b=2;如果想以其他方式提交數(shù)據(jù), 比如contentType:"application/json",即向服務器發(fā)送一個json字符串: $.ajax("/ajax_get",{ data:JSON.stringify({ a:22, b:33 }), contentType:"application/json", type:"POST", }); //{a: 22, b: 33} 注意:contentType:"application/json"一旦設定,data必須是json字符串,不能是json對象 views.py: json.loads(request.body.decode("utf8")) ######################------------traditional---------################ traditional:一般是我們的data數(shù)據(jù)有數(shù)組時會用到 :data:{a:22,b:33,c:["x","y"]}, traditional為false會對數(shù)據(jù)進行深層次迭代;
響應參數(shù)
/* dataType: 預期服務器返回的數(shù)據(jù)類型,服務器端返回的數(shù)據(jù)會根據(jù)這個值解析后,傳遞給回調函數(shù)。 默認不需要顯性指定這個屬性,ajax會根據(jù)服務器返回的content Type來進行轉換; 比如我們的服務器響應的content Type為json格式,這時ajax方法就會對響應的內容 進行一個json格式的轉換,if轉換成功,我們在success的回調函數(shù)里就會得到一個json格式 的對象;轉換失敗就會觸發(fā)error這個回調函數(shù)。如果我們明確地指定目標類型,就可以使用 data Type。 dataType的可用值:html|xml|json|text|script 見下dataType實例 */
小練習:計算兩個數(shù)的和
方式一:這里沒有指定contentType:默認是urlencode的方式發(fā)的
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width"> <title>Title</title> <script src="/static/jquery-3.2.1.min.js"></script> <script src="http://apps.bdimg.com/libs/jquery.cookie/1.4.1/jquery.cookie.js"></script> </head> <body> <h1>計算兩個數(shù)的和,測試ajax</h1> <input type="text" class="num1">+<input type="text" class="num2">=<input type="text" class="ret"> <button class="send_ajax">sendajax</button> <script> $(".send_ajax").click(function () { $.ajax({ url:"/sendAjax/", type:"post", headers:{"X-CSRFToken":$.cookie('csrftoken')}, data:{ num1:$(".num1").val(), num2:$(".num2").val(), }, success:function (data) { alert(data); $(".ret").val(data) } }) }) </script> </body> </html>
views.py
def index(request): return render(request,"index.html") def sendAjax(request): print(request.POST) print(request.GET) print(request.body) num1 = request.POST.get("num1") num2 = request.POST.get("num2") ret = float(num1)+float(num2) return HttpResponse(ret)
方式二:指定conentType為json數(shù)據(jù)發(fā)送:
index2.html
<script> $(".send_ajax").click(function () { $.ajax({ url:"/sendAjax/", type:"post", headers:{"X-CSRFToken":$.cookie('csrftoken')}, //如果是json發(fā)送的時候要用headers方式解決forbidden的問題 data:JSON.stringify({ num1:$(".num1").val(), num2:$(".num2").val() }), contentType:"application/json", //客戶端告訴瀏覽器是以json的格式發(fā)的數(shù)據(jù),所以的吧發(fā)送的數(shù)據(jù)轉成json字符串的形式發(fā)送 success:function (data) { alert(data); $(".ret").val(data) } }) }) </script>
views.py
def sendAjax(request): import json print(request.POST) #<QueryDict: {}> print(request.GET) #<QueryDict: {}> print(request.body) #b'{"num1":"2","num2":"2"}' 注意這時的數(shù)據(jù)不再POST和GET里,而在body中 print(type(request.body.decode("utf8"))) # <class 'str'> # 所以取值的時候得去body中取值,首先得反序列化一下 data = request.body.decode("utf8") data = json.loads(data) num1= data.get("num1") num2 =data.get("num2") ret = float(num1)+float(num2) return HttpResponse(ret)
二、JS實現(xiàn)的ajax
1、AJAX核心(XMLHttpRequest)
其實AJAX就是在Javascript中多添加了一個對象:XMLHttpRequest對象。所有的異步交互都是使用XMLHttpServlet對象完成的。也就是說,我們只需要學習一個Javascript的新對象即可。
var xmlHttp = new XMLHttpRequest();(大多數(shù)瀏覽器都支持DOM2規(guī)范)
注意,各個瀏覽器對XMLHttpRequest的支持也是不同的!為了處理瀏覽器兼容問題,給出下面方法來創(chuàng)建XMLHttpRequest對象:
function createXMLHttpRequest() { var xmlHttp; // 適用于大多數(shù)瀏覽器,以及IE7和IE更高版本 try{ xmlHttp = new XMLHttpRequest(); } catch (e) { // 適用于IE6 try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { // 適用于IE5.5,以及IE更早版本 try{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){} } } return xmlHttp; }
2、使用流程
1、打開與服務器的連接(open)
當?shù)玫絏MLHttpRequest對象后,就可以調用該對象的open()方法打開與服務器的連接了。open()方法的參數(shù)如下:
open(method, url, async):
method:請求方式,通常為GET或POST;
url:請求的服務器地址,例如:/ajaxdemo1/AServlet,若為GET請求,還可以在URL后追加參數(shù);
async:這個參數(shù)可以不給,默認值為true,表示異步請求;
var xmlHttp = createXMLHttpRequest();
xmlHttp.open("GET", "/ajax_get/?a=1", true);
2、發(fā)送請求
當使用open打開連接后,就可以調用XMLHttpRequest對象的send()方法發(fā)送請求了。send()方法的參數(shù)為POST請求參數(shù),即對應HTTP協(xié)議的請求體內容,若是GET請求,需要在URL后連接參數(shù)。
注意:若沒有參數(shù),需要給出null為參數(shù)!若不給出null為參數(shù),可能會導致FireFox瀏覽器不能正常發(fā)送請求!
xmlHttp.send(null);
3、接收服務器的響應(5個狀態(tài),4個過程)
當請求發(fā)送出去后,服務器端就開始執(zhí)行了,但服務器端的響應還沒有接收到。接下來我們來接收服務器的響應。
XMLHttpRequest對象有一個onreadystatechange事件,它會在XMLHttpRequest對象的狀態(tài)發(fā)生變化時被調用。下面介紹一下XMLHttpRequest對象的5種狀態(tài):
0:初始化未完成狀態(tài),只是創(chuàng)建了XMLHttpRequest對象,還未調用open()方法;
1:請求已開始,open()方法已調用,但還沒調用send()方法;
2:請求發(fā)送完成狀態(tài),send()方法已調用;
3:開始讀取服務器響應;
4:讀取服務器響應結束。
onreadystatechange事件會在狀態(tài)為1、2、3、4時引發(fā)。
下面代碼會被執(zhí)行四次!對應XMLHttpRequest的四種狀態(tài)!
xmlHttp.onreadystatechange = function() { alert('hello'); };
但通常我們只關心最后一種狀態(tài),即讀取服務器響應結束時,客戶端才會做出改變。我們可以通過XMLHttpRequest對象的readyState屬性來得到XMLHttpRequest對象的狀態(tài)。
xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { alert('hello'); } };
其實我們還要關心服務器響應的狀態(tài)碼xmlHttp.status是否為200,其服務器響應為404,或500,那么就表示請求失敗了。我們可以通過XMLHttpRequest對象的status屬性得到服務器的狀態(tài)碼。
最后,我們還需要獲取到服務器響應的內容,可以通過XMLHttpRequest對象的responseText得到服務器響應內容。
xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { alert(xmlHttp.responseText); } };
需要注意的:
如果是post請求:
基于JS的ajax沒有Content-Type這個參數(shù)了,也就不會默認是urlencode這種形式了,需要我們自己去設置 <1>需要設置請求頭:xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”); 注意 :form表單會默認這個鍵值對不設定,Web服務器會忽略請求體的內容。 <2>在發(fā)送時可以指定請求體了:xmlHttp.send(“username=yuan&password=123”) 基于jQuery的ajax和form發(fā)送的請求,都會默認有Content-Type,默認urlencode, Content-Type:客戶端告訴服務端我這次發(fā)送的數(shù)據(jù)是什么形式的 dataType:客戶端期望服務端給我返回我設定的格式
如果是get請求:
xmlhttp.open("get","/sendAjax/?a=1&b=2");
小練習:和上面的練習一樣,只是換了一種方式(可以和jQuery的對比一下)
<script> 方式一======================================= //基于JS實現(xiàn)實現(xiàn)用urlencode的方式 var ele_btn = document.getElementsByClassName("send_ajax")[0]; ele_btn.onclick = function () { //綁定事件 alert(5555); //發(fā)送ajax:有一下幾步 //(1)獲取XMLResquest對象 xmlhttp = new XMLHttpRequest(); //(2)連接服務器 //get請求的時候,必用send發(fā)數(shù)據(jù),直接在請求路徑里面發(fā) {# xmlhttp.open("get","/sendAjax/?a=1&b=2");//open里面的參數(shù),請求方式,請求路徑#} //post請求的時候,需要用send發(fā)送數(shù)據(jù) xmlhttp.open("post","/sendAjax/"); //設置請求頭的Content-Type xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //(3)發(fā)送數(shù)據(jù) var ele_num1 = document.getElementsByClassName("num1")[0]; var ele_num2 = document.getElementsByClassName("num2")[0]; var ele_ret = document.getElementsByClassName("ret")[0]; var ele_scrf = document.getElementsByName("csrfmiddlewaretoken")[0]; var s1 = "num1="+ele_num1.value; var s2 = "num2="+ele_num2.value; var s3 = "&csrfmiddlewaretoken="+ele_scrf.value; xmlhttp.send(s1+"&"+s2+s3); //請求數(shù)據(jù) //(4)回調函數(shù),success xmlhttp.onreadystatechange = function () { if (this.readyState==4&&this.status==200){ alert(this.responseText); ele_ret.value = this.responseText } } } 方式二==================================================== {# ===================json=============#} var ele_btn=document.getElementsByClassName("send_ajax")[0]; ele_btn.onclick=function () { // 發(fā)送ajax // (1) 獲取 XMLHttpRequest對象 xmlHttp = new XMLHttpRequest(); // (2) 連接服務器 // get //xmlHttp.open("get","/sendAjax/?a=1&b=2"); // post xmlHttp.open("post","/sendAjax/"); // 設置請求頭的Content-Type var ele_csrf=document.getElementsByName("csrfmiddlewaretoken")[0]; xmlHttp.setRequestHeader("Content-Type","application/json"); xmlHttp.setRequestHeader("X-CSRFToken",ele_csrf.value); //利用js的方式避免forbidden的解決辦法 // (3) 發(fā)送數(shù)據(jù) var ele_num1 = document.getElementsByClassName("num1")[0]; var ele_num2 = document.getElementsByClassName("num2")[0]; var ele_ret = document.getElementsByClassName("ret")[0]; var s1 = ele_num1.value; var s2 = ele_num2.value; xmlHttp.send(JSON.stringify( {"num1":s1,"num2":s2} )) ; // 請求體數(shù)據(jù) // (4) 回調函數(shù) success xmlHttp.onreadystatechange = function() { if(this.readyState==4 && this.status==200){ console.log(this.responseText); ele_ret.value = this.responseText } }; } </script>
views.py
def sendAjax(request): num1=request.POST.get("num1") num2 = request.POST.get("num2") ret = float(num1)+float(num2) return HttpResponse(ret)
JS實現(xiàn)ajax小結
創(chuàng)建XMLHttpRequest對象; 調用open()方法打開與服務器的連接; 調用send()方法發(fā)送請求; 為XMLHttpRequest對象指定onreadystatechange事件函數(shù),這個函數(shù)會在 XMLHttpRequest的1、2、3、4,四種狀態(tài)時被調用; XMLHttpRequest對象的5種狀態(tài),通常我們只關心4狀態(tài)。 XMLHttpRequest對象的status屬性表示服務器狀態(tài)碼,它只有在readyState為4時才能獲取到。 XMLHttpRequest對象的responseText屬性表示服務器響應內容,它只有在 readyState為4時才能獲取到!
總結:
- 如果"Content-Type"="application/json",發(fā)送的數(shù)據(jù)是對象形式的{},需要在body里面取數(shù)據(jù),然后反序列化 = 如果"Content-Type"="application/x-www-form-urlencoded",發(fā)送的是/index/?name=haiyan&agee=20這樣的數(shù)據(jù), 如果是POST請求需要在POST里取數(shù)據(jù),如果是GET,在GET里面取數(shù)據(jù)
實例(用戶名是否已被注冊)
7.1 功能介紹
在注冊表單中,當用戶填寫了用戶名后,把光標移開后,會自動向服務器發(fā)送異步請求。服務器返回true或false,返回true表示這個用戶名已經(jīng)被注冊過,返回false表示沒有注冊過。
客戶端得到服務器返回的結果后,確定是否在用戶名文本框后顯示“用戶名已被注冊”的錯誤信息!
7.2 案例分析
頁面中給出注冊表單;
在username表單字段中添加onblur事件,調用send()方法;
send()方法獲取username表單字段的內容,向服務器發(fā)送異步請求,參數(shù)為username;
django 的視圖函數(shù):獲取username參數(shù),判斷是否為“yuan”,如果是響應true,否則響應false
參考代碼:
<script type="text/javascript"> function createXMLHttpRequest() { try { return new XMLHttpRequest(); } catch (e) { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { return new ActiveXObject("Microsoft.XMLHTTP"); } } } function send() { var xmlHttp = createXMLHttpRequest(); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { if(xmlHttp.responseText == "true") { document.getElementById("error").innerText = "用戶名已被注冊!"; document.getElementById("error").textContent = "用戶名已被注冊!"; } else { document.getElementById("error").innerText = ""; document.getElementById("error").textContent = ""; } } }; xmlHttp.open("POST", "/ajax_check/", true, "json"); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); var username = document.getElementById("username").value; xmlHttp.send("username=" + username); } </script> //--------------------------------------------------index.html <h1>注冊</h1> <form action="" method="post"> 用戶名:<input id="username" type="text" name="username" onblur="send()"/><span id="error"></span><br/> 密 碼:<input type="text" name="password"/><br/> <input type="submit" value="注冊"/> </form> //--------------------------------------------------views.py from django.views.decorators.csrf import csrf_exempt def login(request): print('hello ajax') return render(request,'index.html') # return HttpResponse('helloyuanhao') @csrf_exempt def ajax_check(request): print('ok') username=request.POST.get('username',None) if username=='yuan': return HttpResponse('true') return HttpResponse('false')
三、同源策略與jsonp
同源策略(Same origin policy)是一種約定,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,則瀏覽器的正常功能可能都會受到影響??梢哉fWeb是構建在同源策略基礎之上的,瀏覽器只是針對同源策略的一種實現(xiàn)。
同源策略,它是由Netscape提出的一個著名的安全策略?,F(xiàn)在所有支持JavaScript 的瀏覽器都會使用這個策略。所謂同源是指,域名,協(xié)議,端口相同。當一個瀏覽器的兩個tab頁中分別打開來 百度和谷歌的頁面當瀏覽器的百度tab頁執(zhí)行一個腳本的時候會檢查這個腳本是屬于哪個頁面的,即檢查是否同源,只有和百度同源的腳本才會被執(zhí)行。如果非同源,那么在請求數(shù)據(jù)時,瀏覽器會在控制臺中報一個異常,提示拒絕訪問。
jsonp(jsonpadding)
之前發(fā)ajax的時候都是在自己給自己的當前的項目下發(fā)
現(xiàn)在我們來實現(xiàn)跨域發(fā)。給別人的項目發(fā)數(shù)據(jù),
創(chuàng)建兩個項目,先來測試一下
項目一:
<body> <h1>項目一</h1> <button class="send_jsonp">jsonp</button> <script> $(".send_jsonp").click(function () { $.ajax({ url:"http://127.0.0.1:8080/ajax_send2/", #去請求項目二中的url success:function (data) { console.log(data) } }) }) </script> </body>
項目二:
=========================index.html=============== <h1>項目二</h1> <button class="send_jsonp">jsonp</button> <script> $(".send_jsonp").click(function () { $.ajax({ url:"/ajax_send2/", success:function (data) { console.log(data) } }) }) </script> </body> =========================views=============== from django.shortcuts import render,HttpResponse # Create your views here. def index(request): return render(request, "index.html") def ajax_send2(request): print(222222) return HttpResponse("hello")
出現(xiàn)了一個錯誤,這是因為同源策略給限制了,這是游覽器給我們報的一個錯
(但是注意,項目2中的訪問已經(jīng)發(fā)生了,說明是瀏覽器對非同源請求返回的結果做了攔截。)
注意:a標簽,form,img標簽,引用cdn的css等也屬于跨域(跨不同的域拿過來文件來使用),不是所有的請求都給做跨域,(為什么要進行跨域呢?因為我想用人家的數(shù)據(jù),所以得去別人的url中去拿,借助script標簽)
如果用script請求的時候也會報錯,當你你返回的數(shù)據(jù)是一個return Httpresponse(“項目二”)只是一個名字而已,js中如果有一個變量沒有聲明,就會報錯。就像下面的這樣了
<script src="http://127.0.0.1:8080/ajax_send2/"> 項目二 </script>
只有發(fā)ajax的時候給攔截了,所以要解決的問題只是針對ajax請求能夠實現(xiàn)跨域請求
解決同源策源的兩個方法:
1、jsonp(將JSON數(shù)據(jù)填充進回調函數(shù),這就是JSONP的JSON+Padding的含義。)
jsonp是json用來跨域的一個東西。原理是通過script標簽的跨域特性來繞過同源策略。
思考:這算怎么回事?
<script src="http://code.jquery.com/jquery-latest.js"></script>
借助script標簽,實現(xiàn)跨域請求,示例:
所以只是單純的返回一個也沒有什么意義,我們需要的是數(shù)據(jù)
如下:可以返回一個字典,不過也可以返回其他的(簡單的解決了跨域,利用script)
項目一:
<body> <h1>項目一</h1> <button class="send_jsonp">jsonp</button> <script> $(".send_jsonp").click(function () { $.ajax({ url:"", success:function (data) { console.log(data) } }) }); function func(arg) { console.log(arg) } </script> <script src="http://127.0.0.1:8080/ajax_send2/"></script> </body>
項目二:
def ajax_send2(request): import json print(222222) # return HttpResponse("func('name')") s = {"name":"haiyan","age":12} # return HttpResponse("func('name')") return HttpResponse("func('%s')"%json.dumps(s)) #返回一個func()字符串,正好自己的ajax里面有個func函數(shù),就去執(zhí)行func函數(shù)了, arg就是傳的形參
這樣就會取到值了
這其實就是JSONP的簡單實現(xiàn)模式,或者說是JSONP的原型:創(chuàng)建一個回調函數(shù),然后在遠程服務上調用這個函數(shù)并且將JSON 數(shù)據(jù)形式作為參數(shù)傳遞,完成回調。
將JSON數(shù)據(jù)填充進回調函數(shù),這就是JSONP的JSON+Padding的含義。
但是以上的方式也有不足,回調函數(shù)的名字和返回的那個名字的一致。并且一般情況下,我們希望這個script標簽能夠動態(tài)的調用,而不是像上面因為固定在html里面所以沒等頁面顯示就執(zhí)行了,很不靈活。我們可以通過javascript動態(tài)的創(chuàng)建script標簽,這樣我們就可以靈活調用遠程服務了。
解決辦法:javascript動態(tài)的創(chuàng)建script標簽
===========================jQuery實現(xiàn)===================== {# 創(chuàng)建一個script標簽,讓他請求一次,請求完了刪除他#} //動態(tài)生成一個script標簽,直接可以定義個函數(shù),放在函數(shù)里面 function add_script(url) { var ele_script = $("<script>"); ele_script.attr("src",url); ele_script.attr("id","script"); $("body").append(ele_script); $("#script").remove() } $(".kuayu").click(function () { add_script("http://127.0.0.1:8080/ajax_send2/") }); </script> ==================js實現(xiàn)========================== <button onclick="f()">sendAjax</button> <script> function addScriptTag(src){ var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.src = src; document.body.appendChild(script); document.body.removeChild(script); } function func(name){ alert("hello"+name) } function f(){ addScriptTag("http://127.0.0.1:7766/SendAjax/") } </script>
為了更加靈活,現(xiàn)在將你自己在客戶端定義的回調函數(shù)的函數(shù)名傳送給服務端,服務端則會返回以你定義的回調函數(shù)名的方法,將獲取的json數(shù)據(jù)傳入這個方法完成回調:
function f(){ addScriptTag("http://127.0.0.1:7766/SendAjax/?callbacks=func") }
將視圖views改為
def SendAjax(request): import json dic={"k1":"v1"} print("callbacks:",request.GET.get("callbacks")) callbacks=request.GET.get("callbacks") #注意要在服務端得到回調函數(shù)名的名字 return HttpResponse("%s('%s')"%(callbacks,json.dumps(dic)))
四、jQuery對JSONP的實現(xiàn)
getJSON
jQuery框架也當然支持JSONP,可以使用$.getJSON(url,[data],[callback])方法
<button onclick="f()">sendAjax</button> <script> function f(){ $.getJSON("http://127.0.0.1:7766/SendAjax/?callbacks=?",function(arg){ alert("hello"+arg) }); 匿名函數(shù) } </script>
8002的views不改動。
結果是一樣的,要注意的是在url的后面必須添加一個callback參數(shù),這樣getJSON方法才會知道是用JSONP方式去訪問服務,callback后面的那個?是內部自動生成的一個回調函數(shù)名。
此外,如果說我們想指定自己的回調函數(shù)名,或者說服務上規(guī)定了固定回調函數(shù)名該怎么辦呢?我們可以使用$.ajax方法來實現(xiàn)
$.ajax
<script> function f(){ $.ajax({ url:"http://127.0.0.1:7766/SendAjax/", dataType:"jsonp", jsonp: 'callbacks', #鍵 jsonpCallback:"SayHi" #函數(shù)的名字 }); } function SayHi(arg){ alert(arg); } </script>
8002的views不改動。
當然,最簡單的形式還是通過回調函數(shù)來處理:
<script> function f(){ $.ajax({ url:"http://127.0.0.1:7766/SendAjax/", dataType:"jsonp", //必須有,告訴server,這次訪問要的是一個jsonp的結果。 jsonp: 'callbacks', //jQuery幫助隨機生成的:callbacks="wner" success:function(data){ alert("hi "+data) } }); } </script>
jsonp: 'callbacks'就是定義一個存放回調函數(shù)的鍵,jsonpCallback是前端定義好的回調函數(shù)方法名'SayHi',server端接受callback鍵對應值后就可以在其中填充數(shù)據(jù)打包返回了;
jsonpCallback參數(shù)可以不定義,jquery會自動定義一個隨機名發(fā)過去,那前端就得用回調函數(shù)來處理對應數(shù)據(jù)了。利用jQuery可以很方便的實現(xiàn)JSONP來進行跨域訪問?! ?/p>
注意 JSONP一定是GET請求
五、應用
// 跨域請求實例 $(".jiangxiTV").click(function () { $.ajax({ url:"http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403", dataType: 'jsonp', jsonp: 'callback', jsonpCallback: 'list', success:function (data) { console.log(data.data); // [{},{},{},{},{},{}] week_list=data.data; $.each(week_list,function (i,j) { console.log(i,j); // 1 {week: "周一", list: Array(19)} s="<p>"+j.week+"列表</p>"; $(".show_list").append(s); $.each(j.list,function (k,v) { // {time: "0030", name: "通宵劇場六集連播", link: "http://www.jxntv.cn/live/jxtv2.shtml"} a="<p><a href='"+v.link+"'>"+v.name+"</a></p>"; $(".show_list").append(a); }) }) } }) })
以上這篇JS實現(xiàn)的ajax和同源策略(實例講解)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
JavaScript 手動實現(xiàn)instanceof的方法
instanceof運算符用于檢測構造函數(shù)的prototype屬性是否出現(xiàn)在某個實例對象的原型鏈上,本文重點給大家介紹JavaScript手動實現(xiàn)instanceof的問題,感興趣的朋友跟隨小編一起看看吧2021-10-10web-view內嵌H5與uniapp數(shù)據(jù)的實時傳遞解決方案
這篇文章主要介紹了web-view內嵌H5與uniapp數(shù)據(jù)的實時傳遞,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07