問答
1.ajax 是什么?有什么作用?
AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML),它是通過原生的XMLHttpRequest對象發出HTTP請求,數據通常會以JSON的格式來進行發送,得到服務器返回的數據后,再進行處理。
AJAX通過在后臺與服務器進行少量數據交換,可以使網頁實現異步更新。它可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。
2.前后端開發聯調需要注意哪些事情?后端接口完成前如何 mock 數據?(npm install -g server-mock)
①需要注意的事情有:
約定好數據和接口
例如:
約定數據:需要傳輸的數據;
約定接口:接口名稱,請求和響應的格式;
②MOCK數據的方法有:
使用server-mock或mock.js搭建模擬服務器,進行模擬測試;
使用XAMPP等工具,編寫PHP文件來進行測試
3.點擊按鈕,使用 ajax 獲取數據,如何在數據到來之前防止重復點擊?
可使用狀態鎖的方式:
var lock=false; //設置初始值是false,解鎖狀態
btn.addEventListener('click',function(){
if(lock){ //先判斷一次,這里是false不執行,true的話就return
return;
};
lock=true; //如果程序運行到這里的話,重復點擊的話會return出去
ajax({
to do:function(){
.... //執行完某個動作后解鎖
locked=false
}
})
});
代碼
1.封裝一個 ajax 函數,能通過如下方式調用
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('出錯了')
}
})
});
function ajax(opts){
//這里是創建ajax對象,獲取ajax對象的后臺響應文本
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){ //在ajax上綁定事件監聽
if(xmlhttp.readyState==="4" && xmlhttp.status==="200"){
var json=JSON.parse(xmlhttp.responseText);
//把字符串形式的responseText轉為JSON對象
opts.success(json);
}
if(xmlhttp.readyState==="4" && xmlhttp.status==="404"){ //ajax通信失敗,報錯
opts.error();
}
};
//這里是為了獲得數據,然后把數據變成key=value的形式
var dataStr =" "; //聲明一個空字符串dataStr
for(var key in opts.data){ //使用for in遍歷opts.data對象,變為鍵值對形式
dataStr +=key + "=" + opts.data[key] + "&";//把opts.data對象中每一項的key 和對應的值提取出來拼裝進字符串dataStr
};
dataStr=dataStr.substr(0,dataStr.length-1);
//這里是ajax對象兩種數據傳輸類型
if(opts.type.toLowerCase()==="get"){ //如果是get類型,url后面加上數據
xmlhttp.open("GET",opts.url+"?"+dataStr,true); //連接服務器
xmlhttp.send(); //發送數據過去
};
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里面發送數據,同時在發送前面加上ajax頭部
};
}
2、實現如下加載更多的功能
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>內容1</li>
<li>內容2</li>
</ul>
<div id="btn">點我加載更多</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('出錯了');
};
</script>
</body>
</html>
PHP代碼
<?php
$start = $_GET['begin'];
$len = $_GET['len'];
$items = array();
for($i = 0; $i < $len; $i++){
array_push($items, '內容' . ($start+$i+1));
}
echo json_encode($items);
?>
3.實現注冊表單驗證功能
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>注冊</h1>
<form id="regForm" action>
<dl class="regCt"> //注意這里最好是用dl標簽
<dt>用戶名:</dt>
<dd><input id="username" type="text" placeholder="用戶名hunger已注冊"></dd>
<dd class="intro intro_user">只能是字母、數值、下劃線,3-10個字符</dd>
<dt>密碼:</dt>
<dd><input id="psdStart" type="password"></dd>
<dd class="intro intro_psd1">大寫字母、小寫、數字、下劃線最少兩種,6-15個字符</dd>
<dt>再輸一次:</dt>
<dd><input id="psdAgain" type="password" placeholder="再輸入一次密碼"></dd>
<dd class="intro intro_psd2"></dd>
<dd><button id="btn" type="button">注冊</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(); //用戶名要滿足格式正確,不能重復注冊
});
psdStart.addEventListener('change',function(){
testPass1(); //密碼1要滿足格式正確,與密碼2的輸入相同
});
psdAgain.addEventListener('change',function(){
testPass2(); //同理
});
btn.addEventListener('click',function(){
//點擊btn,執行函數時里面判斷語句要用戶名格式正確,兩個密碼格式也正確才會輸出
if(testName() && testPass1() && testPass2()){
alert('registering....');
console.log('registering.....')
}
});
//檢查用戶名是否可用
//解釋:輸入的用戶名后,服務器接受用戶名,然后判斷是否重復用戶名,如果是重復的話給瀏覽器一個數據,如果不重復給另外一個數據。瀏覽器通過給的數據進行判斷,執行動作給出對應的提示
function testUnValid(){
ajax({ //立即執行函數ajax,參數是對象
url:'task24-3.php', //發送給服務器的地址
type:'get', //使用get方式發送,也就是地址后面加上數據的key=value的形式
data:{ //發送的數據,值是對象
username:username.value,
},
success:function(ret){ //服務器發送數據成功,ret就代表responseText
if(ret=='1'){ //判斷語句,如果后臺發送的數據是1,證明用戶名重復
addClass(username,'error'); //添加error樣式,框變紅
intro_user.innerText="用戶名已經存在"; //框下面給出提示
}else{
removeClass(username,'error'); //否則證明用戶名不重復
intro_user.innerText="用戶名可用";
}
},
error:function(){ //這里是服務器發送數據失敗
console.log('出錯了');
}
});
}
// 檢查用戶名格式是否正確
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事件中的判斷語句調用
}else{
removeClass(psdAgain,'error'); //否則刪除error的樣式
intro_psd2.innerText=''; //框下面沒有任何提示,表示值相等
return true; //返回true,同上
}
}
//這里檢查用戶名輸入的是否滿足要求
function isValidUn(str){
//合法的用戶名, 3~10個字符,只能是字母,數字,下劃線
if(/^[A-Za-z_0-9]{3,10}$/.test(str)){
return true; //使用正則的test判斷,滿足要求就返回true
}else{
return false;
}
}
//這里檢查密碼輸入是不是滿足要求
function isValidPass(str){
//合法的密碼, 6-15個字符,至少包括大寫,小寫,下劃線,數字兩種
if(str.length < 6 || str.length >15){
return false;
}
//如果包含上述四種以外的字符,false
if(/[^A-Za-z_0-9]/.test(str)){
return false;
}
//如果全為大寫、小寫、下劃線、數字, 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);
?>