在平時的開發(fā)項目中,難免接觸前端的知識,需要寫接口,有時候用到j(luò)s中的ajax跨越請求,總結(jié)了ajax的寫法。
開始之前,需要準備兩個文件,ajax.php ;ajax.html
1.ajax的基本步驟(ajax.php)
//1.創(chuàng)建對象
var ajax = new XMLHttpRequest();
// alert(typeof ajax);
//2.建立連接
ajax.open('get', 'ajax.php?id=5', true);
//3.發(fā)送請求
ajax.send();
//4.準備事件處理結(jié)果
ajax.onreadystatechange = function()
{
if (ajax.readyState == 4 && ajax.status == 200) {
//請求: request
//響應: response
var res = ajax.responseText;
// alert(res);
document.write(res);
}
}
ajax,有同步異步的區(qū)別?異步:把小弟派出去了,什么時候回來,什么時候處理它,主程序繼續(xù)執(zhí)行,不會等待。同步:(比較少用)會在send這一步等待,主程序不會繼續(xù)執(zhí)行。method:請求的類型;GET 或 POST 。
2.ajax封裝為函數(shù)(ajax.php)
<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);
}
}
}
//回調(diào) + 匿名
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。
3.jq中的ajax請求(ajax.php)
$.ajax({
url: 'ajax.php?id=5',
dataType: 'json', //指定返回數(shù)據(jù)的類型:xml, html, script, json, text, _default (不要騙他)
type: 'get', //設(shè)置請求的類型:get(默認) post
// data: 'name=123&age=18', //傳輸?shù)臄?shù)據(jù)(有兩種格式)
data: {age:8}, //傳輸?shù)臄?shù)據(jù)
async: true, //同步異步:true 默認異步 false 同步
success: function(res) {
// alert(typeof res);
// alert(res.id);
alert(123);
},
error: function(a){
alert('出錯鳥~~~');
}
});
4.ajax跨域問題(ajax.php)
協(xié)議、域名、端口這三個有任何一個不同,就跨域了。ajax本身是不可以跨域的,通過產(chǎn)生一個script標簽來實現(xiàn)跨域。因為script標簽的src屬性是沒有跨域的限制的。其實設(shè)置了dataType: 'jsonp'后,$.ajax方法就和ajax XmlHttpRequest沒什么關(guān)系了,取而代之的則是JSONP協(xié)議。JSONP是一個非官方的協(xié)議,它允許在服務器端集成Script tags返回至客戶端,通過javascript callback的形式實現(xiàn)跨域訪問。
實現(xiàn)ajax的跨域請求,有幾種方法,這兒寫一種通過‘jsonp’,實現(xiàn)跨域的方法
<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);
//處理接收到的數(shù)據(jù)
},
//end
error:function(e){
alert("error");
}
});
</script>