Ajax基本使用
“偽”AJAX
由于HTML標簽的iframe標簽具有局部加載內容的特性,所以可以使用其來偽造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)用于創建請求參數:method: 請求方式(字符串類型),如:POST、GET、DELETE...url: 要請求的地址(字符串類型)async: 是否異步(布爾類型)b. void send(String body)用于發送請求參數:body: 要發送的數據(字符串類型)c. void setRequestHeader(String header,String value)用于設置請求頭參數:header: 請求頭的key(字符串類型)vlaue: 請求頭的value(字符串類型)d. String getAllResponseHeaders()獲取所有響應頭返回值:響應頭數據(字符串類型)e. String getResponseHeader(String header)獲取響應頭中指定header的值參數:header: 響應頭的key(字符串類型)返回值:響應頭中指定的header對應的值f. void abort()終止請求XmlHttpRequest對象的主要方法 View CodeXmlHttpRequest對象的主要屬性:
a. Number readyState狀態值(整數)詳細:0-未初始化,尚未調用open()方法;1-啟動,調用了open()方法,未調用send()方法;2-發送,已經調用了send()方法,未接收到響應;3-接收,已經接收到部分響應數據;4-完成,已經接收到全部響應數據;b. Function onreadystatechange當readyState的值改變時自動觸發執行其對應的函數(回調函數)c. String responseText服務器返回的數據(字符串類型)d. XmlDocument responseXML服務器返回的數據(Xml對象)e. Number states狀態碼(整數),如:200、404...f. String statesText狀態文本(字符串),如:OK、NotFound... View Code2、跨瀏覽器支持
XmlHttpRequest
IE7+, Firefox, Chrome, Opera, etc.
ActiveXObject("Microsoft.XMLHTTP")
IE6, IE5
jQuery Ajax
jQuery Ajax本質 XMLHttpRequest 或 ActiveXObject?
jQuery.get(...)所有參數:url: 待載入頁面的URL地址data: 待發送 Key/value 參數。 success: 載入成功時回調函數。dataType: 返回內容格式,xml, json, script, text, htmljQuery.post(...)所有參數:url: 待載入頁面的URL地址data: 待發送 Key/value 參數 success: 載入成功時回調函數dataType: 返回內容格式,xml, json, script, text, htmljQuery.getJSON(...)所有參數:url: 待載入頁面的URL地址data: 待發送 Key/value 參數。 success: 載入成功時回調函數。jQuery.getScript(...)所有參數:url: 待載入頁面的URL地址data: 待發送 Key/value 參數。 success: 載入成功時回調函數。jQuery.ajax(...)部分參數:url:請求地址type:請求方式,GET、POST(1.9.0之后用method)headers:請求頭data:要發送的數據contentType:即將發送信息至服務器的內容編碼類型(默認: "application/x-www-form-urlencoded; charset=UTF-8")async:是否異步timeout:設置請求超時時間(毫秒)beforeSend:發送請求前執行的函數(全局)complete:完成之后執行的回調函數(全局)success:成功之后執行的回調函數(全局)error:失敗之后執行的回調函數(全局)accepts:通過請求頭發送給服務器,告訴服務器當前客戶端課接受的數據類型dataType:將服務器端返回的數據轉換成指定類型"xml": 將服務器端返回的內容轉換成xml格式"text": 將服務器端返回的內容轉換成普通文本格式"html": 將服務器端返回的內容轉換成普通文本格式,在插入DOM中時,如果包含JavaScript標簽,則會嘗試去執行。"script": 嘗試將返回值當作JavaScript去執行,然后再將服務器端返回的內容轉換成普通文本格式"json": 將服務器端返回的內容轉換成相應的JavaScript對象"jsonp": JSONP 格式使用 JSONP 形式調用函數時,如 "myurl?callback=?" jQuery 將自動替換 ? 為正確的函數名,以執行回調函數如果不指定,jQuery 將自動根據HTTP包MIME信息返回相應類型(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: 轉換器,將服務器端的內容根據指定的dataType轉換類型,并傳值給success回調函數$.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
由于瀏覽器存在同源策略機制,同源策略阻止從一個源加載的文檔或腳本獲取或設置另一個源加載的文檔的屬性。
1、JSONP實現跨域請求
JSONP(JSONP - JSON with Padding是JSON的一種“使用模式”),利用script標簽的src屬性(瀏覽器允許script標簽跨域)
<!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實現跨域Ajax - Demo2、基于cors實現AJAX請求:
a、支持跨域,簡單請求
服務器設置響應頭: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
在跨域請求中,默認情況下,HTTP Authentication信息,Cookie頭以及用戶的SSL證書無論在預檢請求中或是在實際請求都是不會被發送。
如果想要發送:
- 瀏覽器端:XMLHttpRequest的withCredentials為true
- 服務器端:Access-Control-Allow-Credentials為true
- 注意:服務器端響應的?Access-Control-Allow-Origin 不能是通配符 *
轉載于:https://www.cnblogs.com/Erick-L/p/6867945.html
總結
- 上一篇: codeforces 808 E. Se
- 下一篇: ubuntu卸载vsftpd出错