問(wèn)答
1.ajax 是什么?有什么作用?
AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML),它是通過(guò)原生的XMLHttpRequest對(duì)象發(fā)出HTTP請(qǐng)求,數(shù)據(jù)通常會(huì)以JSON的格式來(lái)進(jìn)行發(fā)送,得到服務(wù)器返回的數(shù)據(jù)后,再進(jìn)行處理。
AJAX通過(guò)在后臺(tái)與服務(wù)器進(jìn)行少量數(shù)據(jù)交換,可以使網(wǎng)頁(yè)實(shí)現(xiàn)異步更新。它可以在不重新加載整個(gè)網(wǎng)頁(yè)的情況下,對(duì)網(wǎng)頁(yè)的某部分進(jìn)行更新。
2.前后端開(kāi)發(fā)聯(lián)調(diào)需要注意哪些事情?后端接口完成前如何 mock 數(shù)據(jù)?(npm install -g server-mock)
①需要注意的事情有:
約定好數(shù)據(jù)和接口
例如:
約定數(shù)據(jù):需要傳輸?shù)臄?shù)據(jù);
約定接口:接口名稱,請(qǐng)求和響應(yīng)的格式;
②MOCK數(shù)據(jù)的方法有:
使用server-mock或mock.js搭建模擬服務(wù)器,進(jìn)行模擬測(cè)試;
使用XAMPP等工具,編寫(xiě)PHP文件來(lái)進(jìn)行測(cè)試
3.點(diǎn)擊按鈕,使用 ajax 獲取數(shù)據(jù),如何在數(shù)據(jù)到來(lái)之前防止重復(fù)點(diǎn)擊?
可使用狀態(tài)鎖的方式:
var lock=false; //設(shè)置初始值是false,解鎖狀態(tài)
btn.addEventListener('click',function(){
if(lock){ //先判斷一次,這里是false不執(zhí)行,true的話就return
return;
};
lock=true; //如果程序運(yùn)行到這里的話,重復(fù)點(diǎn)擊的話會(huì)return出去
ajax({
to do:function(){
.... //執(zhí)行完某個(gè)動(dòng)作后解鎖
locked=false
}
})
});
代碼
1.封裝一個(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ò)了')
}
})
});
function ajax(opts){
//這里是創(chuàng)建ajax對(duì)象,獲取ajax對(duì)象的后臺(tái)響應(yīng)文本
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){ //在ajax上綁定事件監(jiān)聽(tīng)
if(xmlhttp.readyState==="4" && xmlhttp.status==="200"){
var json=JSON.parse(xmlhttp.responseText);
//把字符串形式的responseText轉(zhuǎn)為JSON對(duì)象
opts.success(json);
}
if(xmlhttp.readyState==="4" && xmlhttp.status==="404"){ //ajax通信失敗,報(bào)錯(cuò)
opts.error();
}
};
//這里是為了獲得數(shù)據(jù),然后把數(shù)據(jù)變成key=value的形式
var dataStr =" "; //聲明一個(gè)空字符串dataStr
for(var key in opts.data){ //使用for in遍歷opts.data對(duì)象,變?yōu)殒I值對(duì)形式
dataStr +=key + "=" + opts.data[key] + "&";//把opts.data對(duì)象中每一項(xiàng)的key 和對(duì)應(yīng)的值提取出來(lái)拼裝進(jìn)字符串dataStr
};
dataStr=dataStr.substr(0,dataStr.length-1);
//這里是ajax對(duì)象兩種數(shù)據(jù)傳輸類型
if(opts.type.toLowerCase()==="get"){ //如果是get類型,url后面加上數(shù)據(jù)
xmlhttp.open("GET",opts.url+"?"+dataStr,true); //連接服務(wù)器
xmlhttp.send(); //發(fā)送數(shù)據(jù)過(guò)去
};
if(opts.type.toLowerCase()==="post"){
xmlhttp.open("POST",opts.url,true);
xmlhttp.setRuquestHeader("Content-Type","application/x-www-form-urlencoded")
xmlhttp.send(dataStr); //如果是post類型,send里面發(fā)送數(shù)據(jù),同時(shí)在發(fā)送前面加上ajax頭部
};
}
2、實(shí)現(xiàn)如下加載更多的功能
HTML代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<style>
body,ul,li{
margin:0px;
padding:0px;
}
li{
list-style: none;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
text-align: left;
}
li:hover{
cursor: pointer;
color: #fff;
background:green;
}
#btn{
height: 50px;
width: 100px;
color:#E27272;
text-align: center;
line-height: 50px;
border: 1px solid #E27272;
border-radius: 4px;
margin:20px auto;
}
#btn:hover{
cursor: pointer;
}
</style>
</head>
<body>
<ul id="content">
<li>內(nèi)容1</li>
<li>內(nèi)容2</li>
</ul>
<div id="btn">點(diǎn)我加載更多</div>
<script>
function ajax(opts){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
opts.success(json);
}
if (xhr.readyState == 4 && xhr.status == 404) {
opts.error();
}
};
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"){
xhr.open(opts.type,opts.url+"?"+dataStr,true);
xhr.send();
}
if (opts.type.toLowerCase()=="post"){
xhr.open(opts.type,opts.url,true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(dataStr);
}
}
var btn=document.querySelector('#btn');
var lock=false;
btn.addEventListener('click',function(){
if(lock) {
return;
};
lock=true;
ajax({
type:'get',
url:'task24-2.php',
data:{
begin:document.querySelector('#content').children.length,
len:4
},
success:function(arr){
dealWith(arr);
lock=false;
},
error:function(){
onError();
}
})
});
function dealWith(arr){
for(var i=0;i<arr.length;i++){
var newLi=document.createElement('li');
newLi.innerHTML=arr[i];
document.querySelector('#content').appendChild(newLi)
}
}
function onError(){
console.log('出錯(cuò)了');
};
</script>
</body>
</html>
PHP代碼
<?php
$start = $_GET['begin'];
$len = $_GET['len'];
$items = array();
for($i = 0; $i < $len; $i++){
array_push($items, '內(nèi)容' . ($start+$i+1));
}
echo json_encode($items);
?>
3.實(shí)現(xiàn)注冊(cè)表單驗(yàn)證功能
HTML代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<style>
*{
box-sizing:border-box;
margin:0px;
padding: 0px;
}
h1{
margin-bottom: 20px;
}
#register{
/*border:1px solid;*/
margin:50px;
}
.regCt dt{
/*border: 1px solid;*/
float: left;
height: 25px;
line-height: 25px;
font-size: 14px;
width:90px;
}
.regCt dd{
margin-left: 90px;
}
.regCt input{
height: 25px;
line-height: 25px;
padding-left: 10px;
border-radius: 4px;
border: 1px solid #ccc;
}
.regCt .error{
border-color: red;
}
.regCt .intro{
/*border: 1px solid;*/
height: 10px;
margin-top: 15px;
margin-bottom: 15px;
font-size: 12px;
color: #aaa;
}
</style>
</head>
<body1>
<div id="register">
<h1>注冊(cè)</h1>
<form id="regForm" action>
<dl class="regCt"> //注意這里最好是用dl標(biāo)簽
<dt>用戶名:</dt>
<dd><input id="username" type="text" placeholder="用戶名hunger已注冊(cè)"></dd>
<dd class="intro intro_user">只能是字母、數(shù)值、下劃線,3-10個(gè)字符</dd>
<dt>密碼:</dt>
<dd><input id="psdStart" type="password"></dd>
<dd class="intro intro_psd1">大寫(xiě)字母、小寫(xiě)、數(shù)字、下劃線最少兩種,6-15個(gè)字符</dd>
<dt>再輸一次:</dt>
<dd><input id="psdAgain" type="password" placeholder="再輸入一次密碼"></dd>
<dd class="intro intro_psd2"></dd>
<dd><button id="btn" type="button">注冊(cè)</button></dd>
</dl>
</form>
</div>
<script>
var username=document.querySelector("#username"),
psdStart=document.querySelector("#psdStart"),
psdAgain=document.querySelector("#psdAgain"),
btn=document.querySelector("#btn"),
intro_user=document.querySelector(".intro_user"),
intro_psd1=document.querySelector(".intro_psd1"),
intro_psd2=document.querySelector(".intro_psd2");
username.addEventListener('change',function(){
testName() && testUnValid(); //用戶名要滿足格式正確,不能重復(fù)注冊(cè)
});
psdStart.addEventListener('change',function(){
testPass1(); //密碼1要滿足格式正確,與密碼2的輸入相同
});
psdAgain.addEventListener('change',function(){
testPass2(); //同理
});
btn.addEventListener('click',function(){
//點(diǎn)擊btn,執(zhí)行函數(shù)時(shí)里面判斷語(yǔ)句要用戶名格式正確,兩個(gè)密碼格式也正確才會(huì)輸出
if(testName() && testPass1() && testPass2()){
alert('registering....');
console.log('registering.....')
}
});
//檢查用戶名是否可用
//解釋:輸入的用戶名后,服務(wù)器接受用戶名,然后判斷是否重復(fù)用戶名,如果是重復(fù)的話給瀏覽器一個(gè)數(shù)據(jù),如果不重復(fù)給另外一個(gè)數(shù)據(jù)。瀏覽器通過(guò)給的數(shù)據(jù)進(jìn)行判斷,執(zhí)行動(dòng)作給出對(duì)應(yīng)的提示
function testUnValid(){
ajax({ //立即執(zhí)行函數(shù)ajax,參數(shù)是對(duì)象
url:'task24-3.php', //發(fā)送給服務(wù)器的地址
type:'get', //使用get方式發(fā)送,也就是地址后面加上數(shù)據(jù)的key=value的形式
data:{ //發(fā)送的數(shù)據(jù),值是對(duì)象
username:username.value,
},
success:function(ret){ //服務(wù)器發(fā)送數(shù)據(jù)成功,ret就代表responseText
if(ret=='1'){ //判斷語(yǔ)句,如果后臺(tái)發(fā)送的數(shù)據(jù)是1,證明用戶名重復(fù)
addClass(username,'error'); //添加error樣式,框變紅
intro_user.innerText="用戶名已經(jīng)存在"; //框下面給出提示
}else{
removeClass(username,'error'); //否則證明用戶名不重復(fù)
intro_user.innerText="用戶名可用";
}
},
error:function(){ //這里是服務(wù)器發(fā)送數(shù)據(jù)失敗
console.log('出錯(cuò)了');
}
});
}
// 檢查用戶名格式是否正確
function testName(){
if(!isValidUn(username.value)){
addClass(username,'error');
intro_user.innerText='用戶名格式不正確';
return false;
}else{
removeClass(username,'error');
intro_user.innerText='用戶名可用';
return true;
}
}
//檢查密碼框1的格式是否正確,同理
function testPass1(){
if(!isValidPass(psdStart.value)){
addClass(psdStart,'error');
intro_psd1.innerText='密碼格式不正確';
return false;
}else{
removeClass(psdStart,'error');
intro_psd1.innerText='';
return true;
}
}
//檢查密碼框2的密碼是否與密碼框1的密碼相等
function testPass2(){
if(psdAgain.value !== psdStart.value){ //這里是不相等,怎樣提示
addClass(psdAgain,'error'); //添加error的樣式,框變紅
intro_psd2.innerText='兩次密碼輸入不一樣'; //框下面的提示
return false; //返回false,使btn事件中的判斷語(yǔ)句調(diào)用
}else{
removeClass(psdAgain,'error'); //否則刪除error的樣式
intro_psd2.innerText=''; //框下面沒(méi)有任何提示,表示值相等
return true; //返回true,同上
}
}
//這里檢查用戶名輸入的是否滿足要求
function isValidUn(str){
//合法的用戶名, 3~10個(gè)字符,只能是字母,數(shù)字,下劃線
if(/^[A-Za-z_0-9]{3,10}$/.test(str)){
return true; //使用正則的test判斷,滿足要求就返回true
}else{
return false;
}
}
//這里檢查密碼輸入是不是滿足要求
function isValidPass(str){
//合法的密碼, 6-15個(gè)字符,至少包括大寫(xiě),小寫(xiě),下劃線,數(shù)字兩種
if(str.length < 6 || str.length >15){
return false;
}
//如果包含上述四種以外的字符,false
if(/[^A-Za-z_0-9]/.test(str)){
return false;
}
//如果全為大寫(xiě)、小寫(xiě)、下劃線、數(shù)字, false
if (/(^[a-z]+$)|(^[A-Z]+$)|(^_+$)|(^\d+$)/g.test(str)) {
return false;
}
return true;
}
//添加刪除class
function addClass(ele,cls){
ele.className +=' '+cls;
}
function removeClass(ele,cls){
ele.className=ele.className.replace(new RegExp('\\b'+cls+'\\b','g'),'');
}
function ajax(opts){
var xhr;
if (window.XMLHttpRequest) { //IE7+,chrome,Safari,Opera,Firefox
xhr = new XMLHttpRequest();
} else {
xhr = new AcitveXObject("Microsoft.XMLHTTP"); //IE5,IE6
}
// var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState===4 && xhr.status===200){
var json=JSON.parse(xhr.responseText);
opts.success(json);
}
if(xhr.readState===4 && xhr.status===404){
opts.error();
}
}
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'){
xhr.open(opts.type,opts.url + "?" + dataStr,true);
xhr.send();
}
if(opts.type.toLowerCase()==='post'){
xhr.open(opts.type,opts.url,true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send(dataStr);
}
}
</script>
</body>
</html>
PHP代碼
<?php
$name = $_GET['username'];
if($name === 'hunger'){
$ret = 1;
}else{
$ret = 0;
}
echo json_encode($ret);
?>