Ajax基本使用
“偽”AJAX
由于HTML標(biāo)簽的iframe標(biāo)簽具有局部加載內(nèi)容的特性,所以可以使用其來偽造Ajax請求。
<!DOCTYPE html> <html><head lang="en"><meta charset="UTF-8"><title></title></head><body><div><p>請輸入要加載的地址:<span id="currentTime"></span></p><p><input id="url" type="text" /><input type="button" value="刷新" onclick="LoadPage();"></p></div><div><h3>加載頁面位置:</h3><iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe></div><script type="text/javascript">window.onload= function(){var myDate = new Date();document.getElementById('currentTime').innerText = myDate.getTime();};function LoadPage(){var targetUrl = document.getElementById('url').value;document.getElementById("iframePosition").src = targetUrl;}</script></body> </html> View Code原生AJAX
Ajax主要就是使用 【XmlHttpRequest】對象來完成請求的操作
1、XmlHttpRequest對象介紹
XmlHttpRequest對象的主要方法:
a. void open(String method,String url,Boolen async)用于創(chuàng)建請求參數(shù):method: 請求方式(字符串類型),如:POST、GET、DELETE...url: 要請求的地址(字符串類型)async: 是否異步(布爾類型)b. void send(String body)用于發(fā)送請求參數(shù):body: 要發(fā)送的數(shù)據(jù)(字符串類型)c. void setRequestHeader(String header,String value)用于設(shè)置請求頭參數(shù):header: 請求頭的key(字符串類型)vlaue: 請求頭的value(字符串類型)d. String getAllResponseHeaders()獲取所有響應(yīng)頭返回值:響應(yīng)頭數(shù)據(jù)(字符串類型)e. String getResponseHeader(String header)獲取響應(yīng)頭中指定header的值參數(shù):header: 響應(yīng)頭的key(字符串類型)返回值:響應(yīng)頭中指定的header對應(yīng)的值f. void abort()終止請求XmlHttpRequest對象的主要方法 View CodeXmlHttpRequest對象的主要屬性:
a. Number readyState狀態(tài)值(整數(shù))詳細(xì):0-未初始化,尚未調(diào)用open()方法;1-啟動(dòng),調(diào)用了open()方法,未調(diào)用send()方法;2-發(fā)送,已經(jīng)調(diào)用了send()方法,未接收到響應(yīng);3-接收,已經(jīng)接收到部分響應(yīng)數(shù)據(jù);4-完成,已經(jīng)接收到全部響應(yīng)數(shù)據(jù);b. Function onreadystatechange當(dāng)readyState的值改變時(shí)自動(dòng)觸發(fā)執(zhí)行其對應(yīng)的函數(shù)(回調(diào)函數(shù))c. String responseText服務(wù)器返回的數(shù)據(jù)(字符串類型)d. XmlDocument responseXML服務(wù)器返回的數(shù)據(jù)(Xml對象)e. Number states狀態(tài)碼(整數(shù)),如:200、404...f. String statesText狀態(tài)文本(字符串),如:OK、NotFound... View Code2、跨瀏覽器支持
XmlHttpRequest
IE7+, Firefox, Chrome, Opera, etc.
ActiveXObject("Microsoft.XMLHTTP")
IE6, IE5
jQuery Ajax
jQuery Ajax本質(zhì) XMLHttpRequest 或 ActiveXObject?
jQuery.get(...)所有參數(shù):url: 待載入頁面的URL地址data: 待發(fā)送 Key/value 參數(shù)。 success: 載入成功時(shí)回調(diào)函數(shù)。dataType: 返回內(nèi)容格式,xml, json, script, text, htmljQuery.post(...)所有參數(shù):url: 待載入頁面的URL地址data: 待發(fā)送 Key/value 參數(shù) success: 載入成功時(shí)回調(diào)函數(shù)dataType: 返回內(nèi)容格式,xml, json, script, text, htmljQuery.getJSON(...)所有參數(shù):url: 待載入頁面的URL地址data: 待發(fā)送 Key/value 參數(shù)。 success: 載入成功時(shí)回調(diào)函數(shù)。jQuery.getScript(...)所有參數(shù):url: 待載入頁面的URL地址data: 待發(fā)送 Key/value 參數(shù)。 success: 載入成功時(shí)回調(diào)函數(shù)。jQuery.ajax(...)部分參數(shù):url:請求地址type:請求方式,GET、POST(1.9.0之后用method)headers:請求頭data:要發(fā)送的數(shù)據(jù)contentType:即將發(fā)送信息至服務(wù)器的內(nèi)容編碼類型(默認(rèn): "application/x-www-form-urlencoded; charset=UTF-8")async:是否異步timeout:設(shè)置請求超時(shí)時(shí)間(毫秒)beforeSend:發(fā)送請求前執(zhí)行的函數(shù)(全局)complete:完成之后執(zhí)行的回調(diào)函數(shù)(全局)success:成功之后執(zhí)行的回調(diào)函數(shù)(全局)error:失敗之后執(zhí)行的回調(diào)函數(shù)(全局)accepts:通過請求頭發(fā)送給服務(wù)器,告訴服務(wù)器當(dāng)前客戶端課接受的數(shù)據(jù)類型dataType:將服務(wù)器端返回的數(shù)據(jù)轉(zhuǎn)換成指定類型"xml": 將服務(wù)器端返回的內(nèi)容轉(zhuǎn)換成xml格式"text": 將服務(wù)器端返回的內(nèi)容轉(zhuǎn)換成普通文本格式"html": 將服務(wù)器端返回的內(nèi)容轉(zhuǎn)換成普通文本格式,在插入DOM中時(shí),如果包含JavaScript標(biāo)簽,則會(huì)嘗試去執(zhí)行。"script": 嘗試將返回值當(dāng)作JavaScript去執(zhí)行,然后再將服務(wù)器端返回的內(nèi)容轉(zhuǎn)換成普通文本格式"json": 將服務(wù)器端返回的內(nèi)容轉(zhuǎn)換成相應(yīng)的JavaScript對象"jsonp": JSONP 格式使用 JSONP 形式調(diào)用函數(shù)時(shí),如 "myurl?callback=?" jQuery 將自動(dòng)替換 ? 為正確的函數(shù)名,以執(zhí)行回調(diào)函數(shù)如果不指定,jQuery 將自動(dòng)根據(jù)HTTP包MIME信息返回相應(yīng)類型(an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a stringconverters: 轉(zhuǎn)換器,將服務(wù)器端的內(nèi)容根據(jù)指定的dataType轉(zhuǎn)換類型,并傳值給success回調(diào)函數(shù)$.ajax({accepts: {mycustomtype: 'application/x-some-custom-type'},// Expect a `mycustomtype` back from serverdataType: 'mycustomtype'// Instructions for how to deserialize a `mycustomtype` converters: {'text mycustomtype': function(result) {// Do Stuffreturn newresult;}},}); jQuery Ajax 方法列表 <!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title> </head> <body><p><input type="button" οnclick="XmlSendRequest();" value='Ajax請求' /></p><script type="text/javascript" src="jquery-1.12.4.js"></script><script>function JqSendRequest(){$.ajax({url: "http://c2.com:8000/test/",type: 'GET',dataType: 'text',success: function(data, statusText, xmlHttpRequest){console.log(data);}})}</script> </body> </html> 基于jQueryAjax - Demo跨域AJAX
由于瀏覽器存在同源策略機(jī)制,同源策略阻止從一個(gè)源加載的文檔或腳本獲取或設(shè)置另一個(gè)源加載的文檔的屬性。
1、JSONP實(shí)現(xiàn)跨域請求
JSONP(JSONP - JSON with Padding是JSON的一種“使用模式”),利用script標(biāo)簽的src屬性(瀏覽器允許script標(biāo)簽跨域)
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title> </head> <body><p><input type="button" οnclick="Jsonp1();" value='提交'/></p><p><input type="button" οnclick="Jsonp2();" value='提交'/></p><script type="text/javascript" src="jquery-1.12.4.js"></script><script>function Jsonp1(){var tag = document.createElement('script');tag.src = "http://c2.com:8000/test/";document.head.appendChild(tag);document.head.removeChild(tag);}function Jsonp2(){$.ajax({url: "http://c2.com:8000/test/",type: 'GET',dataType: 'JSONP',success: function(data, statusText, xmlHttpRequest){console.log(data);}})}</script> </body> </html> 基于JSONP實(shí)現(xiàn)跨域Ajax - Demo2、基于cors實(shí)現(xiàn)AJAX請求:
a、支持跨域,簡單請求
服務(wù)器設(shè)置響應(yīng)頭:Access-Control-Allow-Origin = '域名' 或 '*'
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title> </head> <body><p><input type="submit" οnclick="XmlSendRequest();" /></p><p><input type="submit" οnclick="JqSendRequest();" /></p><script type="text/javascript" src="jquery-1.12.4.js"></script><script>function XmlSendRequest(){var xhr = new XMLHttpRequest();xhr.onreadystatechange = function(){if(xhr.readyState == 4) {var result = xhr.responseText;console.log(result);}};xhr.open('GET', "http://c2.com:8000/test/", true);xhr.send();}function JqSendRequest(){$.ajax({url: "http://c2.com:8000/test/",type: 'GET',dataType: 'text',success: function(data, statusText, xmlHttpRequest){console.log(data);}})}</script> </body> </html> HTML class MainHandler(tornado.web.RequestHandler):def get(self):self.set_header('Access-Control-Allow-Origin', "http://www.xxx.com")self.write('{"status": true, "data": "seven"}')跨域傳輸cookie
在跨域請求中,默認(rèn)情況下,HTTP Authentication信息,Cookie頭以及用戶的SSL證書無論在預(yù)檢請求中或是在實(shí)際請求都是不會(huì)被發(fā)送。
如果想要發(fā)送:
- 瀏覽器端:XMLHttpRequest的withCredentials為true
- 服務(wù)器端:Access-Control-Allow-Credentials為true
- 注意:服務(wù)器端響應(yīng)的?Access-Control-Allow-Origin 不能是通配符 *
轉(zhuǎn)載于:https://www.cnblogs.com/Erick-L/p/6867945.html
總結(jié)
- 上一篇: codeforces 808 E. Se
- 下一篇: 读书笔记之启示录