ajax優(yōu)勢
一次http請求對應(yīng)一個(gè)頁面
ajax,局部刷新頁面缰雇,客戶端(瀏覽器)就能與服務(wù)端進(jìn)行通信
異步加載數(shù)據(jù),無需切換頁面
ajax請求過程:
- 創(chuàng)建XMLHttpRequest對象,也就是創(chuàng)建一個(gè)異步調(diào)用對象
- 創(chuàng)建一個(gè)新的HTTP請求,并指定該HTTP請求的方法嘹屯、URL及驗(yàn)證信息
- 設(shè)置響應(yīng)HTTP請求狀態(tài)變化的函數(shù)
- 發(fā)送HTTP請求
- 獲取異步調(diào)用返回的數(shù)據(jù)
- 使用JavaScript和DOM實(shí)現(xiàn)局部刷新
js原生方法請求json數(shù)據(jù):
網(wǎng)址:http://developer.baidu.com/map/carapi-7.htm
<select id="city">
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="深圳">深圳</option>
<option value="廣州">廣州</option>
</select>
<div id="detail"></div>
<script type="text/javascript">
var city = document.getElementById('city');
var detail = document.getElementById('detail');
function addURI(url,name,value){
url += url.indexOf('?')==-1?'?':'&';
//encodeURIComponent() 函數(shù)可把字符串作為 URI 組件進(jìn)行編碼。
url += encodeURLComponent(name)+"="+encodeURLComponent(value);
return url;
}
city.onchange = function(){
//創(chuàng)建對象 兼容le
if(window.XMLHttpRequest){
var xhr = new XMLHttpRequest();
}else{
var xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
var url =addURI('weather.php','city',this.value);
xhr.onload = function(){
//狀態(tài)碼 status 200=ok 404="未找到"
if(xhr.status>=200&&xhr.status<300||xhr.status==304){
console.log(xhr.responseText);
//JSON.parse()方法將一個(gè) JSON字符串解析成一個(gè)javascript值从撼。
var res = JSON.parse(xhr.responseText);
//基于json數(shù)組
var today = res.results[0].weather_data[0];
console.log(today);
//定義一個(gè)變量儲(chǔ)存輸出
var html = "";
// for in 循環(huán)數(shù)組
for(var a in today){
html += today[a]+"<br>";
}
detail.innerHTML = html;
}else{
console.log('error='+xhr.status);
}
}
//響應(yīng) true(異步)或 false(同步)
xhr.open('get',url,true);
xhr.send(null);
}
</script>
php:
<?php
header('Content-Type:text/html;charset=utf8');
$city = $_GET["city"];
$url = "http://api.map.baidu.com/telematics/v3/weather?location=".$city."&output=json&ak=cTk2xI05KkdzSdC2oMqpu8WHX0puzdBo";
echo file_get_contents($url);
?>
jq ajax方法:
<body>
<input type="text" id="word">
<div id="detail"></div>
<script src="jquery-1.11.3.min.js" charset="utf-8"></script>
<script type="text/javascript">
var detail = document.getElementById('detail');
$("#word").on('input',function(){
$.ajax({
//請求地址
url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+$(this).val()+'&json=1&cb=?',
type:'GET', //請求類型
dataType:'jsonp', //預(yù)期請求數(shù)據(jù)類型
success:function(res){
//成功的回調(diào)
console.log(res.s)
var xyy = res.s
var html ="";
for(var a in xyy){
html += xyy[a] + "<br>";
}
detail.innerHTML = html
},
error:function(err){
console.log(err)
}
})
})
</script>
</body>