傳統(tǒng)方法的缺點(diǎn):
傳統(tǒng)的web交互是用戶觸發(fā)一個(gè)http請求服務(wù)器,然后服務(wù)器收到之后,在做出響應(yīng)到用戶,并且返回一個(gè)新的頁面,每當(dāng)服務(wù)器處理客戶端提交的請求時(shí),客戶都只能空閑等待,并且哪怕只是一次很小的交互、只需從服務(wù)器端得到很簡單的一個(gè)數(shù)據(jù),都要返回一個(gè)完整的html頁,而用戶每次都要浪費(fèi)時(shí)間和帶寬去重新讀取整個(gè)頁面。這個(gè)做法浪費(fèi)了許多帶寬,由于每次應(yīng)用的交互都需要向服務(wù)器發(fā)送請求,應(yīng)用的響應(yīng)時(shí)間就依賴于服務(wù)器的響應(yīng)時(shí)間。這導(dǎo)致了用戶界面的響應(yīng)比本地應(yīng)用慢得多。
什么是ajax?
ajax的出現(xiàn),剛好解決了傳統(tǒng)方法的缺陷。ajax 是一種用于創(chuàng)建快速動態(tài)網(wǎng)頁的技術(shù)。通過在后臺與服務(wù)器進(jìn)行少量數(shù)據(jù)交換,ajax 可以使網(wǎng)頁實(shí)現(xiàn)異步更新。這意味著可以在不重新加載整個(gè)網(wǎng)頁的情況下,對網(wǎng)頁的某部分進(jìn)行更新。
xmlhttprequest 對象
xmlhttprequest對象是ajax的基礎(chǔ),xmlhttprequest 用于在后臺與服務(wù)器交換數(shù)據(jù)。這意味著可以在不重新加載整個(gè)網(wǎng)頁的情況下,對網(wǎng)頁的某部分進(jìn)行更新。目前所有瀏覽器都支持xmlhttprequest
abort() | 停止當(dāng)前請求 |
---|---|
getallresponseheaders() | 把http請求的所有響應(yīng)首部作為鍵/值對返回 |
abort() | 停止當(dāng)前請求 |
getresponseheader(“header”) | 返回指定首部的串值 |
open(“method”,“url”,[asyncflag],[“username”],[“password”]) | 建立對服務(wù)器的調(diào)用。method參數(shù)可以是get(獲取數(shù)據(jù)) 、post(新建 增加數(shù)據(jù))或put(更新 修改數(shù)據(jù) 刪除數(shù)據(jù))。url參數(shù)可以是相對url或絕對url。這個(gè)方法還包括3個(gè)可選的參數(shù),是否異步, 默認(rèn)為true異步 同步是false 同步用戶名,密碼 |
send(content) | 向服務(wù)器發(fā)送請求(500 服務(wù)器報(bào)錯(cuò) 404 頁面丟失 200 success) |
setrequestheader(“header”, “value”) | 把指定首部設(shè)置為所提供的值。在設(shè)置任何首部之前必須先調(diào)用open()。設(shè)置header并和請求一起發(fā)送 ('post'方法一定要 ) |
五步使用法:
1.創(chuàng)建xmlhttprequest對象
2.使用open方法設(shè)置和服務(wù)器的交互信息
3.設(shè)置發(fā)送的數(shù)據(jù),開始和服務(wù)器端交互;send(content)這個(gè)方法里面的參數(shù)可寫可不寫 寫想服務(wù)器傳輸數(shù)據(jù) 不寫是請求數(shù)據(jù)
4.注冊事件
5.更新界面
同步和異步的區(qū)別:
同步是:等待請求完成之后 再去執(zhí)行 異步是:請求和后續(xù)代碼同時(shí)執(zhí)行
如何將原生ajax進(jìn)行封裝
封裝成一個(gè)函數(shù),請求接口時(shí)候需要 路徑 方式 數(shù)據(jù)
<!doctype html> <html> <head lang="en"> <meta charset="utf-8"> <title></title> </head> <body> <script> /* get 方式傳值 是在url 路徑之后?a=1&b=2&n=3 * post 不在路徑上寫 send() 上發(fā)送數(shù)據(jù) * */ function method(res, url, data, callback) { var http = new xmlhttprequest(); if (res == "get") { if (data) { url += "?"; url += data; } http.open(res, url); http.send(); } else { http.open(res, url); if (data) { http.send(data); } else { http.send(); } } http.onreadystatechange = function () { if (http.readystate == 4 && http.status == 200) { callback(json.parse(http.response)); } } } method("post", "./list/data.txt", null, function (data) { console.log(data); }); </script> </body> </html>
js幾種跨域方法和原理
解決ajax跨域
一般ajax跨域解決就是通過jsonp解決或者cors解決,如以下:
js跨域是指通過js在不同的域之間進(jìn)行數(shù)據(jù)傳輸或通信,跨域 : 協(xié)議 端口 主機(jī)名稱不同會產(chǎn)生跨域
第一種方法:jsonp跨域(只支持get請求)
比如,有個(gè)a.html頁面,它里面的代碼需要利用ajax獲取一個(gè)不同域上的json數(shù)據(jù),假設(shè)這個(gè)json數(shù)據(jù)地址是http://example.com/data.php,那么a.html中的代碼就可以這樣:
實(shí)現(xiàn)原理:由于使用script標(biāo)簽調(diào)用遠(yuǎn)程js文件沒有不受跨域的影響,所以可以通過創(chuàng)建一個(gè)script標(biāo)簽,通過src屬性來訪問遠(yuǎn)程文件。
其實(shí)這并不屬于ajax,但是可以實(shí)現(xiàn)類似ajax的功能。
第二種方法:cross 跨域 php 在里面配置 header('access-control-allow-origin: * ');但只支持html5
var http = new xmlhttprequest(); http.open("post", "http://127.0.0.1:8080/0616/insert.php"); http.send(); http.onreadystatechange = function () { if (http.readystate == 4 && http.status == 200) { console.log(http.response); } }
第三種方法:代理
這種方式是通過后臺(asp、php、java、asp.net)獲取其他域名下的內(nèi)容,然后再把獲得內(nèi)容返回到前端,這樣因?yàn)樵谕粋€(gè)域名下,所以就不會出現(xiàn)跨域的問題。
實(shí)現(xiàn)代碼:創(chuàng)建一個(gè)ajax請求(頁面地址為:http://localhost/ajax/proxy.html)
var request = null; if(window.xmlhttprequest) { request = new xmlhttprequest; } else { request = new activexobject("microsoft.xmlhttp"); } request.onreadystatechange = function{ console.log(this.readystate); if(this.readystate===4 && this.status===200) { var resultobj = eval("("+this.responsetext+")"); //將返回的文本數(shù)據(jù)轉(zhuǎn)換json對象 document.getelementbyid("box").innerhtml = resultobj.name+":"+resultobj.sex; //將返回的內(nèi)容顯示在頁面中 } } request.open("post","proxy.php",true); request.setrequestheader("content-type","application/x-www-form-urlencoded"); request.send("name=呂銘印&sex=男");
創(chuàng)建ajax請求。
proxy.php代碼
header("content-type:text/html;charset=utf-8"); $url = "http://localhost:63342/ajax/proxy.js"; $contents = file_get_contents($url); echo $contents;
附:ajax跨域post請求的java代理實(shí)現(xiàn)
最近開發(fā)的項(xiàng)目有個(gè)功能的需求如下:根據(jù)用戶提供的外部鏈接(outter_url),在頁面填寫好查詢條件(param)并向該url發(fā)起查詢請求,查詢返回的數(shù)據(jù)來動態(tài)生成html的table來顯示數(shù)據(jù),同時(shí)要求請求的方法是post請求。
在開發(fā)過程中用的是jquery的異步請求。問題出現(xiàn)了,網(wǎng)上搜了半天沒有發(fā)現(xiàn)實(shí)現(xiàn)jquery跨域進(jìn)行post請求的解決方案(貌似不支持),所以自己用java代碼來發(fā)起post跨域請求
關(guān)于實(shí)現(xiàn)思路的幾點(diǎn)說明:
1)? ? ? 項(xiàng)目中用的是spring,所以這個(gè)請求是在spring某個(gè)controller的方法中實(shí)現(xiàn)的,為了方便說明問題該方法假設(shè)為(ajaxproxy)
2)? ? ? 在jsp頁面中通過jquery的ajax方法,發(fā)起一個(gè)請求,該請求的url映射到1)中所說的那個(gè)ajaxproxy方法,并把查詢條件(param)一起傳遞到ajaxproxy方法.部分代碼如下
$.ajax({ type : "get", //映射到controller對應(yīng)方法的url url : "<c:url value='/user/put/queryitems'/>", //查詢條件數(shù)據(jù) data : param, datatype : 'json', success : function(data) {//動態(tài)生成table,代碼略}
3)? ? ? 在ajaxproxy方法中,用httpurlconnection鏈接outter_url,并設(shè)置connection的請求方法為post,并發(fā)送查詢條件(param),該部分的代碼實(shí)現(xiàn)如下:
url connect = new url(outer_url); httpurlconnection connection =(httpurlconnection)connect.openconnection(); connection.setrequestmethod(“post”); //發(fā)送查詢條件 outputstreamwriter out = new outputstreamwriter(connection.getoutputstream()); out.wirte(param); out.flush();
4)? ? ? 接收數(shù)據(jù)并返回?cái)?shù)據(jù),jsp頁面中ajax的success方法處理接收到的數(shù)據(jù)data,并把data返回就可以了,接收數(shù)據(jù)的代碼如下
stringbuffer data = new stringbuffer(); bufferedreader reader = new bufferedreader(new inputstreamreader(connection.getinputstream(), "gb2312")); string line; while ((line = reader.readline()) != null) { data.append(line); } return data;
綜上所述,實(shí)現(xiàn)跨域post請求的java實(shí)現(xiàn)代碼如下
@requestmapping("queryitems") public @responsebody string ajaxproxy(string name, string starttime, string endtime, string tag, model m, httpservletrequest req) throws unsupportedencodingexception { //拼接查詢條件,組成json格式的數(shù)據(jù)發(fā)送 jsonobject node = new jsonobject(); try { jsonobject param = new jsonobject(); param.put("type", ""); param.put("typevalue", ""); //param.put("key", name); param.put("key", new string(name.tostring().getbytes("utf-8"), "gbk")); param.put("start_time", starttime); param.put("end_time", endtime); param.put("tags", tag); node.put("param", param); jsonobject user = new jsonobject(); user.put("userid", "123"); node.put("user", user); jsonobject device = new jsonobject(); device.put("dnum", "123"); node.put("device", device); jsonobject developer = new jsonobject(); developer.put("apikey", "******"); developer.put("secretkey", "*****"); node.put("developer", developer); node.put("action", action); } catch (jsonexception e1) { // todo auto-generated catch block e1.printstacktrace(); } // 使用post方式向目的服務(wù)器發(fā)送請求 url connect; stringbuffer data = new stringbuffer(); try { connect = new url("outter_url"); httpurlconnection connection = (httpurlconnection)connect.openconnection(); connection.setrequestmethod("post"); connection.setdooutput(true); outputstreamwriter paramout = new outputstreamwriter( connection.getoutputstream(),"utf-8"); paramout.write(json); paramout.flush(); bufferedreader reader = new bufferedreader(new inputstreamreader( connection.getinputstream(), "gb2312")); string line; while ((line = reader.readline()) != null) { data.append(line); } paramout.close(); reader.close(); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } return data.tostring(); }
總結(jié)
到此這篇關(guān)于ajax請求數(shù)據(jù)及實(shí)現(xiàn)跨域的三種方法的文章就介紹到這了,更多相關(guān)ajax請求數(shù)據(jù)及跨域內(nèi)容請搜索碩編程以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持碩編程!