在平時的開發項目中,不免接觸前端的知識,須要寫接口,有時候用到js中的ajax跨越請求,總結了ajax的寫法。javascript
開始以前,須要準備兩個文件,ajax.php ;ajax.htmlphp
1.ajax的基本步驟(ajax.php)html
//1.建立對象
var ajax = new XMLHttpRequest();
// alert(typeof ajax);
//2.創建鏈接
ajax.open('get', 'ajax.php?id=5', true);
//3.發送請求
ajax.send();
//4.準備事件處理結果
ajax.onreadystatechange = function()
{
if (ajax.readyState == 4 && ajax.status == 200) {
//請求: request
//響應: response
var res = ajax.responseText;
// alert(res);
document.write(res);
}
}
ajax,有同步異步的區別?異步:把小弟派出去了,何時回來,何時處理它,主程序繼續執行,不會等待。同步:(比較少用)會在send這一步等待,主程序不會繼續執行。method:請求的類型;GET 或 POST 。前端
2.ajax封裝爲函數(ajax.php)java
<script> function get(url, func) { var ajax = new XMLHttpRequest(); ajax.open('get', url, true); ajax.send(); ajax.onreadystatechange = function() { if (ajax.readyState == 4 && ajax.status == 200) { var res = ajax.responseText; func(res); } } } //回調 + 匿名 get('1.php', function(res){ alert(res); }) get('ajax.php', function(res){ console.log(res); }) /* get('1.php', chuli); function chuli(res) { alert(res); } get('ajax.php', chuli2); function chuli2(res) { console.log(res); } */ </script>
這樣封裝好,就方便咱們使用了,tp框架,ecshop,ecstore,都有本身的封裝的ajax。ajax
3.jq中的ajax請求(ajax.php) json
$.ajax({
url: 'ajax.php?id=5',
dataType: 'json', //指定返回數據的類型:xml, html, script, json, text, _default (不要騙他)
type: 'get', //設置請求的類型:get(默認) post
// data: 'name=123&age=18', //傳輸的數據(有兩種格式) data: {age:8}, //傳輸的數據 async: true, //同步異步:true 默認異步 false 同步 success: function(res) { // alert(typeof res); // alert(res.id); alert(123); }, error: function(a){ alert('出錯鳥~~~'); } });
4.ajax跨域問題(ajax.php)
跨域
協議、域名、端口這三個有任何一個不一樣,就跨域了。ajax自己是不能夠跨域的,經過產生一個script標籤來實現跨域。由於script標籤的src屬性是沒有跨域的限制的。其實設置了dataType: 'jsonp'後,$.ajax方法就和ajax XmlHttpRequest沒什麼關係了,取而代之的則是JSONP協議。JSONP是一個非官方的協議,它容許在服務器端集成Script tags返回至客戶端,經過javascript callback的形式實現跨域訪問。服務器
實現ajax的跨域請求,有幾種方法,這兒寫一種經過‘jsonp’,實現跨域的方法框架
<script type="text/javascript"> var url = 'http://localhost/other.php?act=get_article'; $.ajax({ type : "get", url :url, jsonp: "callbackparam", jsonpCallback:"jsonpCallback1", success : function(data){ var obj = eval(data); //處理接收到的數據 }, //end error:function(e){ alert("error"); } }); </script>
知識更新很快,學習很重要。當回過頭,感受這些很簡單的時候,說明本身在進步,在成長...