1唆途,ajax 是什么?有什么作用肛搬?
- ajax全稱為Asynchronous JavaScript and XML,可以實(shí)現(xiàn)在不重新加載整個(gè)頁(yè)面的情況下蛤奢,對(duì)網(wǎng)頁(yè)的某一部分進(jìn)行更新(異步)让腹。
- ajax在 瀏覽器與web服務(wù)器之間使用異步數(shù)據(jù)傳輸(HTTP請(qǐng)求)從服務(wù)器獲取數(shù)據(jù)。
這里的異步指的是脫離當(dāng)前瀏覽器頁(yè)面的請(qǐng)求瓜晤、加載等單獨(dú)執(zhí)行腹纳,這就意味著可以在不重新加載整個(gè)網(wǎng)頁(yè)的情況下,通過(guò)JavaScript發(fā)送請(qǐng)求足画,接受服務(wù)器傳來(lái)的數(shù)據(jù)佃牛,然后操作DOM將新數(shù)據(jù)對(duì)網(wǎng)頁(yè)的某部分進(jìn)行更新,使用ajax最直觀的感受就是向服務(wù)器獲取新數(shù)據(jù)不需要刷新頁(yè)面等待了象缀。
2爷速,前后端開發(fā)聯(lián)調(diào)需要注意哪些事情?后端接口完成前如何 mock 數(shù)據(jù)莉给?(npm install -g server-mock) 知識(shí)點(diǎn)視頻-如何 mock 數(shù)據(jù)
前后端聯(lián)調(diào)是一種 真實(shí)業(yè)務(wù)數(shù)據(jù)和 本地mock數(shù)據(jù)之間來(lái)回切換以達(dá)到前后端分離架構(gòu)下的不同開發(fā)速度時(shí)數(shù)據(jù)交換的一種方式方法廉沮。
需要注意的事情有:
約定前后端聯(lián)調(diào)的時(shí)間。
約定雙方需要傳輸?shù)臄?shù)據(jù)和接口叁幢,在接口文檔中確定好參數(shù)的名稱漂洋、格式等。
約定請(qǐng)求和響應(yīng)的格式和內(nèi)容演训。
什么是mock數(shù)據(jù):就是html發(fā)送一個(gè)ajax的請(qǐng)求贝咙。這個(gè)請(qǐng)求到哪里去,然后后端如何去響應(yīng)這個(gè)請(qǐng)求窟她。
后端去獲取數(shù)據(jù)蔼水,并且定義接口;
前端編寫頁(yè)面吊说,并且和后端進(jìn)行交互优炬。mock數(shù)據(jù)的方法有:
使用server-mock或mock.js (http://mockjs.com/ )搭建模擬服務(wù)器,進(jìn)行模擬測(cè)試(優(yōu)點(diǎn)是不需要熟練掌握后臺(tái)PHP語(yǔ)言雅宾,采用熟悉的js語(yǔ)法)葵硕;
步驟:安裝node.js,呼出cmd命令
選取一個(gè)文件夾吐辙,使用npm install -g server -mock進(jìn)行全局安裝
輸入mock start可以啟動(dòng)一個(gè)web 服務(wù)器蘸劈,他的根目錄就是你選取的文件夾,啟動(dòng)完成之后贤惯,web服務(wù)器就可以展示了瀏覽器輸入localhost:8080就是你選取的文件夾
使用mock init會(huì)自動(dòng)的在文件夾下生成3個(gè)文件
當(dāng)html使用url對(duì)接口進(jìn)行請(qǐng)求孵构,會(huì)被router.js里相同的接口接受
比如:
app.get("/loadMore",function(req,res){
//接受名為loadMore的php的參數(shù)
res.send({status:0,//向html發(fā)出正確的回參
msg:"hello 饑人谷"http://回參中的值
})
})
- 使用XAMPP等工具烟很,編寫PHP文件來(lái)進(jìn)行測(cè)試蜡镶。
3官还,點(diǎn)擊按鈕毒坛,使用 ajax 獲取數(shù)據(jù),如何在數(shù)據(jù)到來(lái)之前防止重復(fù)點(diǎn)擊?
方法一:使用button的disabled屬性屯伞,配合setTimeout 0豪直,使在數(shù)據(jù)到來(lái)之前按鈕都不能被點(diǎn)擊
el.addEventListener("click",function(){
this.disabled=true; ajax();
setTimeout(this.disabled=false,0);
});
方法二:可設(shè)置標(biāo)記變量flag,初始時(shí)設(shè)置flag為true.在用戶點(diǎn)擊提交按鈕后饵撑,判斷flag是否為true唆貌,如果是則發(fā)送ajax請(qǐng)求,并把flag設(shè)置為false语卤。 等服務(wù)端給出響應(yīng)后再把flag設(shè)置為true;
var ready = true;
$('.add-more').on('click', function(){
...
if(!ready){
return;
}
ready = false;
$.ajax({
...
complete: function(){
ready = true;
}
});
});
- 代碼題:
一酪刀,封裝一個(gè) ajax 函數(shù),能通過(guò)如下方式調(diào)用
function ajax(opts){
// todo ...
}
document.querySelector('#btn').addEventListener('click', function(){
ajax({
url: 'getData.php', //接口地址
type: 'get', // 類型眼滤, post 或者 get,
data: {
username: 'xiaoming',
password: 'abcd1234'
},
success: function(ret){
console.log(ret); // {status: 0}
},
error: function(){
console.log('出錯(cuò)了')
}
})
});
- 未封裝的普通ajax代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<!-- 需求是:在輸入框輸入用戶名诅需,點(diǎn)擊按鈕荧库,打包請(qǐng)求后發(fā)給后臺(tái),后臺(tái)響應(yīng)對(duì)應(yīng)的姓名和年齡 -->
<input type="text" name="username" id="username" placeholder="請(qǐng)輸入用戶名">
<button class="btn">提交</button>
<dl id="ct">
</dl>
<script>
document.querySelector('.btn').addEventListener('click',function(){
var xmlhttp = new XMLHttpRequest();
username = document.querySelector('#username').value;
var url = 'renwu1.php' + '?username='+username;
// GET方式:
xmlhttp.open('GET',url,true);
xmlhttp.send();
//POST方式:
// xmlhttp.open('POST','renwu1.php',true);
// xmlhttp.setRequestHeader("content-type","application/x-www-form-urlencoded");
// xmlhttp.send("username="+username);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var userInfo = JSON.parse(xmlhttp.responseText);
dealWith(userInfo);
}
}
});
function dealWith(userInfo){
var str = '<dt>性別:</dt>';
str += '<dd>'+ userInfo.sex +'</dd>';
str += '<dt>年齡:</dt>';
str += '<dd>'+userInfo.age +'</dd>';
document.querySelector('#ct').innerHTML = str;
}
</script>
</body>
</html>
-
PHP代碼:
<?php // $username = $_GET['username']; $username = $_POST['username']; if($username === 'har'){ $ret = array('sex'=>'男','age'=>'23'); }else if($username === 'marry'){ $ret = array('sex'=>'女','age'=>'22'); }else{ $ret = array('sex'=>'女','age'=>'27'); } echo json_encode($ret); //輸出標(biāo)準(zhǔn)json格式 ?>
封裝
function ajax(opts){
var xmlhttp = new XMLHttpRequest();
var dataStr = '';
for(var key in opts.data){
dataStr += key + '=' + opts.data[key]+'&'
}
dataStr = dataStr.substr(0,dataStr.length-1)
if(opts.type.toLowerCase()==='post'){
xmlhttp.open(opts.type,opts.url,true);
xmlhttp.setRequestHeader('content-type','application/x-www-form-urlencoded');
xmlhttp.send(dataStr);
}
if(opts.type.toLowerCase()==='get'){
xmlhttp.open(opts.type,opts.url+'?'+ dataStr,true);
xmlhttp.send();
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
var json = JSON.parse(xmlhttp.responseText);
opts.success(json);
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 404 ){
opts.error();
}
};
}
document.querySelector('#btn').addEventListener('click', function(){
ajax({
url: 'renwu1.php', //接口地址
type: 'get', // 類型, post 或者 get,
data: {
username: document.querySelector('#username').value;
password: document.querySelector('#password');
},
success: function(jsonData){
dealWith(jsonData); // {status: 0}
},
error: function(){
console.log('出錯(cuò)了')
}
})
});
function dealWith(userInfo){
var str = '<dt>性別:</dt>';
str += '<dd>'+ userInfo.sex +'</dd>';
str += '<dt>年齡:</dt>';
str += '<dd>'+userInfo.age +'</dd>';
document.querySelector('#ct').innerHTML = str;
};
二牵现,封裝一個(gè) ajax 函數(shù),能通過(guò)如下方式調(diào)用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>任務(wù)二</title>
<style media="screen">
div,a{
margin:0;
padding:0;
}
.ct li{
border:1px solid #ccc;
height: 50px;
line-height:50px;
padding-left: 10px;
margin: 10px 0;
list-style:none;
}
.ct{
padding-left: 0px;
}
.btn{
border: 1px solid red;
text-align: center;
display: inline-block;
height: 30px;
width: 80px;
line-height: 30px;
cursor: pointer;
position:absolute;
left:50%;
margin-top: 30px;
margin-left: -40px;
border-radius: 5px;
}
.btn:active{
background-color: pink;
color: #222;
}
</style>
</head>
<body>
<ul class="ct">
<li>內(nèi)容1</li>
<li>內(nèi)容2</li>
</ul>
<a class="btn">加載更多</a>
<script type="text/javascript">
function ajax(opts){
var xml = new XMLHttpRequest();
var datastr = '';
for(var key in opts.data){
datastr += key + '=' + opts.data[key] + '&'
}
datastr=datastr.substr(0,datastr.length-1);
if(opts.type.toLowerCase()=='get'){
xml.open(opts.type,opts.url+'?'+datastr,true);
xml.send();
}
if(opts.type.toLowerCase()=='post'){
xml.open(opts.type,opts.url,true);
xml.send(datastr);
xml.setRequestHeader('content-type','application/x-www-form-urlencoded');
}
xml.onreadystatechange = function(){
if(xml.readyState==4 && xml.status == 200){
var json = JSON.parse(xml.responseText);
opts.success(json);
}
if(xml.readyState==4 && xml.status ==404){
opts.error();
}
}
}
var cur = 3;
document.querySelector('.btn').addEventListener('click', function(){
ajax({
url: 'renwu2.php', //接口地址
type: 'get', // 類型居扒, post 或者 get,
data: {
start:cur,
len: 6
},
success: function(json){
if(json.status==1){
append(json.data);
cur += 6;
}else{
console.log('失敗啦')
} // {status: 0}
},
error: function(){
console.log('出錯(cuò)了')
}
})
});
function append(arr){
for(var i=0; i<arr.length; i++){
var li = document.createElement('li');
li.innerHTML = arr[i];
document.querySelector('.ct').appendChild(li);
}
}
</script>
</body>
</html>
PHP端:
<?php
$start = $_GET['start'];
$len = $_GET['len'];
$items = array();
for($i=0;$i<$len;$i++){
array_push($items,'內(nèi)容'.($start+$i));
}
$ret = array('status'=>1,'data'=>$items);
sleep(1);
echo json_encode($ret);
?>