ajax
ajax一個前后臺配合的技術(shù),它可以讓javascript發(fā)送http請求,與后臺通信,獲取數(shù)據(jù)和信息。ajax技術(shù)的原理是實例化xmlhttp對象,使用此對象與后臺通信。jquery將它封裝成了一個函數(shù)$.ajax(),我們可以直接用這個函數(shù)來執(zhí)行ajax請求。
ajax需要在服務(wù)器環(huán)境下運行。
$.ajax使用方法
常用參數(shù):
1、url 請求地址
2、type 請求方式,默認是’get’,常用的還有’post’
3、dataType 設(shè)置返回的數(shù)據(jù)格式,常用的是’json’格式,也可以設(shè)置為’text’
4、data 設(shè)置發(fā)送給服務(wù)器的數(shù)據(jù)
5、success 設(shè)置請求成功后的回調(diào)函數(shù)
6、error 設(shè)置請求失敗后的回調(diào)函數(shù)
7、async 設(shè)置是否異步,默認值是’true’,表示異步
以前的寫法:
$.ajax({
url: '/change_data',
type: 'get',
dataType: 'json',
data:{'code':300268}
success:function(dat){
alert(dat.name);
},
error:function(){
alert('服務(wù)器超時,請重試!');
}
});
新的寫法(推薦):
$.ajax({
url: '/change_data',
type: 'get',
dataType: 'json',
data:{'code':300268}
})
.done(function(dat) {
alert(dat.name);
})
.fail(function() {
alert('服務(wù)器超時,請重試!');
});
$(function(){
/*$.ajax({
url:'js/data.json',
type:'get',
dataType:'json'
/*success:function(dat){
// console.log(dat);
$('.login_btn').hide();
$('.login_info em').html( dat.name ).parent().show();
},
error:function(){
alert('服務(wù)器超時,請重試!');
}
}).done(function(dat){
$('.login_btn').hide();
$('.login_info em').html( dat.name ).parent().show();
}).fail(function(){
alert('服務(wù)器超時,請重試!');
})
*/
// 上面是完整寫法,可以簡寫成下面$.get的寫法:
$.get('js/data.json',function(dat){
$('.login_btn').hide();
$('.login_info em').html( dat.name ).parent().show();
});
})
ES6語法
ES6是JavaScript語言的新版本,它也可以叫做ES2015,之前學習的JavaScript屬于ES5,ES6在它的基礎(chǔ)上增加了一些語法,ES6是未來JavaScript的趨勢,而且React庫中大量使用了ES6的語法,所以掌握這些常用的ES6語法是必須的。
變量聲明let和const
let和const是新增的聲明變量的開頭的關(guān)鍵字,在這之前,變量聲明是用var關(guān)鍵字,這兩個關(guān)鍵字和var的區(qū)別是,它們聲明的變量沒有預(yù)解析,let和const的區(qū)別是,let聲明的是一般變量,const申明的常量,不可修改。
alert(iNum01) // 彈出undefined
// alert(iNum02); 報錯,let關(guān)鍵字定義變量沒有變量預(yù)解析
// alert(iNum03); 報錯,const關(guān)鍵字定義變量沒有變量預(yù)解析
var iNum01 = 6;
// 使用let關(guān)鍵字定義變量
let iNum02 = 12;
// 使用const關(guān)鍵字定義變量
const iNum03 = 24;
alert(iNum01); // 彈出6
alert(iNum02); // 彈出12
alert(iNum03); // 彈出24
iNum01 = 7;
iNum02 = 13;
//iNum03 = 25; // 報錯,const定義的變量不可修改,const定義的變量是常量
alert(iNum01)
alert(iNum02);
alert(iNum03);
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script>
// 用var定義變量,變量有預(yù)解析的特性
// alert(iNum01);//undefined
var iNum01 = 12;
// alert(iNum01); //12
//let定義的變量沒有預(yù)解析,下面這一句就報錯 在初始化之前無法訪問'iNum02'
// alert(iNum02); //Cannot access 'iNum02' before initialization
let iNum02 = 24;
// alert(iNum02); //24
iNum02 =25;
// alert(iNum02);//25
//const定義的變量沒有預(yù)解析,下面這一句出錯 在初始化之前無法訪問'iNum03'
// alert(iNum03);//Cannot access 'iNum03' before initialization
const iNum03 = 36;
alert(iNum03); //36
//對常量變量賦值。const定義的是常量,它的值不能修改,下面這一句出錯
// iNum03 = 37;
// alert(iNum03);//Assignment to constant variable.
</script>
<body>
</body>
</html>
解構(gòu)賦值
ES6 允許我們按照一定模式,從數(shù)組和對象中提取值,對變量進行賦值,這被稱為解構(gòu)(Destructuring)
1、數(shù)組的解構(gòu)賦值
const arr = [1, 2, 3]
let [a, b, c] = arr
console.log(a, b, c); // 1 2 3
2、對象的解構(gòu)賦值
const obj = { name: 'tom',address:'beijing', age: '100'}
let {name, age} = obj // 變量名稱必須和對象的key同名
console.log(name, age); //tom 100
3、函數(shù)參數(shù)的解構(gòu)賦值
const person = { name: '小明', age: 11}
function printPerson({name, age}) { // 函數(shù)參數(shù)可以解構(gòu)一個對象
console.log(`姓名:${name} 年齡:${age}`);
}
printPerson(person) // 姓名:小明 年齡:11
字符串模板
ES6中提供了模版字符串,用`(反引號)標識,用${}將變量括起來
let name = '小明';
let age = 11;
alert(`我的名字是${name},我的年齡是${age}歲。`)
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
//數(shù)組的解構(gòu)賦值
let aList = [1,2,3];
let [a,b,c] = aList;
console.log(a,b,c);//1 2 3
// 對象的解構(gòu)賦值
let person = {name:"tom",age:18};
let {name,age} = person;
console.log(`姓名:${name} 年齡:${age}`);//姓名:tom 年齡:18
// 函數(shù)參數(shù)的解構(gòu)賦值
function fnAlertPerson({name,age}){
console.log(`我的姓名:${name} 我的年齡:${age}`);
alert(
`我的名字是:${name},
我的年齡是:${age}`
);
}
fnAlertPerson(person); //我的姓名:[object Object] 我的年齡:undefined
</script>
</head>
<body>
</body>
</html>
擴展運算符(…)
擴展運算符(…),它用于把一個數(shù)組轉(zhuǎn)化為用逗號分隔的參數(shù)序列,它常用在不定參數(shù)個數(shù)時的函數(shù)調(diào)用,數(shù)組合并等情形。
let arr = [1,2,3];
let arr2 = [...arr,4];
console.log(arr2) // [1,2,3,4]
function fnAdd(a,b,c){
alert(a + b + c);
}
fnAdd(...arr); // 6
function fnMyalert(...a){
console.log(a);
alert(a[0]);
alert(a[1]);
}
fnMyalert(10,5); // [10,5] 10 5
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
let arr = [1,2,3];
//下面這種方式不能復(fù)制數(shù)組
let arr2 = arr; //只是指向同一個地址
//用for循環(huán)賦值數(shù)組
let arr3 = [];
for (var index = 0; index < arr.length; index++) {
arr3.push(arr[index]);
}
//通過擴展運算符復(fù)制數(shù)組
let arr4 = [...arr,5];
arr.push(4);
// alert(arr); //1 2 3 4
// alert(arr2); //1,2,3,4
// alert(arr3); //1 2 3
alert(arr4); // 1 2 3 5
function fnAdd(a,b,c){
alert(a+b+c);
}
// fnAdd(...arr); //6 把數(shù)據(jù)arr傳進去
function fnConsole(...a){ //10,5,6
console.log(a);
}
fnConsole(10,5,6);
</script>
</head>
<body>
</body>
</html>
箭頭函數(shù)
可以把箭頭函數(shù)理解成匿名函數(shù)的第二種寫法,箭頭函數(shù)的作用是可以在對象中綁定this,解決了JavaScript中this指定混亂的問題。
// 定義函數(shù)的一般方式
/*
function fnRs(a,b){
var rs = a + b;
alert(rs);
}
fnRs(1,2);
*/
// 通過匿名函數(shù)賦值來定義函數(shù)
/*
var fnRs = function(a,b){
var rs = a + b;
alert(rs);
}
fnRs(1,2);
*/
// 通過箭頭函數(shù)的寫法定義
var fnRs = (a,b)=>{
var rs = a + b;
alert(rs);
}
// fnRs(1,2);
// 一個參數(shù)可以省略小括號
var fnRs2 = a =>{
alert(a);
}
fnRs2('haha!');
// 函數(shù)中如果只有一個return語句,return和大括號都可以省略
/*
var fnAdd = function(a,b){
return a + b;
}
*/
var fnAdd = (a,b) => a+b;
// 函數(shù)的返回值如果是javascript對象時,對象需要加括號
/*
let fn = function(){
return {"a":5};
}
*/
// fn = ()=>{"a":5}
// 上面這么寫是錯的,需要寫成下面的形式,返回的對象要加括號
fn = ()=>({"a":5})
示例
// 箭頭函數(shù)的作用,可以綁定對象中的this
var person = {
name:'tom',
age:18,
showName:function(){
setTimeout(()=>{
alert(this.name);
},1000)
}
}
person.showName();
模塊導入import和導出export
javascript之前是沒有模塊的功能的,之前做js模塊化開發(fā),是用的一些js庫來模擬實現(xiàn)的,在ES6中加入了模塊的功能,一個js文件就是一個模塊,js文件中需要先導出(export)后,才能被其他js文件導入(import)
ES6的導出分為名字導出和默認導出
1、名稱導出
導入的變量名必須和導出的變量名一致
// mod01.js文件中導出
export let iNum01 = 12;
export let fnMyalert = function(){
alert('hello');
}
// index.html文件中導入
<script type="module">
import {iNum01,fnMyalert} from "./js/mod01.js";
alert(iNum01);
fnMyalert();
</script>
// mod01.js中還可以寫成如下:
let iNum01 = 12;
let fnMyalert = function(){
alert('hello');
}
export {iNum01,fnMyalert}
2、默認導出(default export) 一個模塊只能有一個默認導出,對于默認導出,導入的名稱可以和導出的名稱不一致,這對于導出匿名函數(shù)或類非常有用。
// mod02.js文件中導出
export default {"name":"tom","age":18}
// index.html文件中導入
<script type="module">
import person from "./js/mod02.js";
alert(person.name);
</script>
對象的簡寫
javascript對象在ES6中可以做一些簡寫形式,了解這些簡寫形式,才能方便我們讀懂一些在javascript代碼中簡寫的對象。
let name = '李思';
let age = 18;
/*
var person = {
name:name,
age:age,
showname:function(){
alert(this.name);
},
showage:function(){
alert(this.age);
}
}
*/
// 簡寫成下面的形式
var person = {
name,
age,
showname(){
alert(this.name);
},
showage(){
alert(this.age);
}
}
person.showname();
person.showage();
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>Document</title>
<script>
let name = "tom";
let age = 18;
// let person = {
// name:name,
// age:age,
// showname:function(){
// console.log(this.name);
// },
// showage:function(){
// console.log(this.age);
// }
// }
//上面對象可以簡寫成下面的形式
let person = {
name,
age,
showname(){
console.log(this.name);
},
showage(){
console.log(this.age);
}
}
person.showname();
person.showage();
</script>
</head>
<body>
</body>
</html>
定義類及類的繼承
ES6 封裝了class語法來大大簡化了類的創(chuàng)建和類的繼承
// 定義類,類的首字母要大寫
class Person {
// 定義構(gòu)造函數(shù)
constructor(name,age){
this.name = name;
this.age = age;
}
// 定義方法
showname(){
alert('我的名字是:' + this.name);
}
showage(){
alert('我的年齡是:' + this.age);
}
}
// 通過類實例化對象
let Andy = new Person('劉德華',55);
// 調(diào)用對象的方法
Andy.showname();
Andy.showage();
// 定義類繼承Person類
class Student extends Person{
constructor(name,age,school){
super(name,age);
this.school = school;
}
showschool(){
alert('我的學校是:' + this.school);
}
}
// 通過類實例化對象
let Tom = new Student('小明','16','北京一中');
// 調(diào)用對象的方法
Tom.showname();
Tom.showschool();
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
//定義一個類
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
showname(){
console.log("我的名稱:"+this.name);
}
showage(){
console.log("我的年齡:"+this.age);
}
}
//通過類來實例化一個對象
let Andy = new Person('劉德華',55);
//調(diào)用對象上面的方法
// Andy.showname();
// Andy.showage();
//定義類繼承Person
class Student extends Person{
constructor(name,age,school){
super(name,age);
this.school = school;
}
showschool(){
console.log("我的學校是:"+this.school);
}
}
var xiaoming = new Student("小明",15,"武漢一中");
xiaoming.showage();
xiaoming.showname();
xiaoming.showschool();
</script>
</head>
<body>
</body>
</html>
異步操作
es6新增了異步操作的寫法,來解決異步操作函數(shù)回調(diào)的問題,這個新增的寫法就是Promise對象,Promise實際上就是一個特殊的Javascript對象,反映了”異步操作的最終值”?!盤romise”直譯過來有預(yù)期的意思,因此,它也代表了某種承諾,即無論你異步操作成功與否,這個對象最終都會返回一個值給你。
在實際開發(fā)中,如果我們在寫ajax程序時,我們?nèi)绻M麅蓚€ajax程序都執(zhí)行完后,再去做一件事情,我們實現(xiàn)的方法可以是,在一個ajax中嵌套另外一個ajax程序:
$.ajax({
url:'data01.json',
type:'get',
dataType:'json',
success:function(dat1){
$.ajax({
url:'data01.json',
type:'get',
dataType:'json',
success:function(dat2){
console.log([dat1,dat2])
}
})
})
上面的寫法不方便編寫,也不方便閱讀,Promise對象就可以解決這個問題
// 實例化一個Promise對象
var pro01 = new Promise(function(resolve,reject){
$.ajax({
url:'js/data01.json',
type:'get',
dataType:'json'
}).done(function(dat){
resolve(dat)
}).fail(function(err){
reject(err)
})
});
var pro02 = new Promise(function(resolve,reject){
$.ajax({
url:'js/data02.json',
type:'get',
dataType:'json'
}).done(function(dat){
resolve(dat)
}).fail(function(err){
reject(err)
})
});
// 通過Promise對象來處理回調(diào)
pro01.then(function(dat){
console.log(dat);
}).catch(function(err){
console.log(err)
})
上面將兩個ajax請求分別放在兩個promise對象中,其中resolve參數(shù)是處理請求成功的回調(diào)函數(shù),reject是處理失敗的回調(diào)函數(shù),接著就可以通過這個對象,來處理ajax的回調(diào),相當于把回調(diào)拆開了寫。 如果希望兩個ajax程序都執(zhí)行完后,再去做一件事情,可以寫成如下的形式:
Promise.all([pro01,pro02]).then(result=>console.log(result));
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/jquery-1.12.4.min.js"></script>
<script>
//方式一
// $.ajax({
// url:'js/data01.json',
// type:'get',
// dataType:'json',
// success: function(dat01){
// // console.log(dat); //{"name": "張三"}
// $.ajax({
// url:'js/data02.json',
// type:'get',
// dataType:'json',
// success: function(dat02){
// // console.log(dat); //{"name": "張三"}
// console.log([dat01,dat02]);
// },
// error: function(err){
// }
// })
// },
// error: function(err){
// }
// })
//方式二
let pro01 = new Promise(function(resolve,reject){
$.ajax({
url:'js/data01.json',
type:'get',
dataType:'json',
success:function(dat){
resolve(dat);
},
error:function(err){
reject(err);
}
})
});
let pro02 = new Promise(function(resolve,reject){
$.ajax({
url:'js/data02.json',
type:'get',
dataType:'json',
success:function(dat){
resolve(dat);
},
error:function(err){
reject(err);
}
})
});
//then請求成功
pro01.then(function(dat){
console.log(dat);
}).catch(function(err){
})
Promise.all([pro01,pro02]).then(re=>{
console.log(re);
})
</script>
</head>
<body>
</body>
</html>
server.js
/*
NodeJS Static Http Server - http://github.com/thedigitalself/node-static-http-server/
By James Wanga - The Digital Self
Licensed under a Creative Commons Attribution 3.0 Unported License.
A simple, nodeJS, http development server that trivializes serving static files.
This server is HEAVILY based on work done by Ryan Florence(https://github.com/rpflorence) (https://gist.github.com/701407). I merged this code with suggestions on handling varied MIME types found at Stackoverflow (http://stackoverflow.com/questions/7268033/basic-static-file-server-in-nodejs).
To run the server simply place the server.js file in the root of your web application and issue the command
$ node server.js
or
$ node server.js 1234
with "1234" being a custom port number"
Your web application will be served at http://localhost:8888 by default or http://localhost:1234 with "1234" being the custom port you passed.
Mime Types:
You can add to the mimeTypes has to serve more file types.
Virtual Directories:
Add to the virtualDirectories hash if you have resources that are not children of the root directory
*/
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;
var mimeTypes = {
"htm": "text/html",
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"gif": "image/gif",
"js": "text/javascript",
"css": "text/css",
"json":"text/json"
};
var virtualDirectories = {
//"images": "../images/"
};
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri)
, root = uri.split("/")[1]
, virtualDirectory;
virtualDirectory = virtualDirectories[root];
if(virtualDirectory){
uri = uri.slice(root.length + 1, uri.length);
filename = path.join(virtualDirectory ,uri);
}
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
console.error('404: ' + filename);
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
console.error('500: ' + filename);
return;
}
var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
response.writeHead(200, {"Content-Type": mimeType});
response.write(file, "binary");
response.end();
console.log('200: ' + filename + ' as ' + mimeType);
});
});
}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
data01.json和data02.json示例
{"name":"張三"} {"name":"李思"}
使用node server.js
新增數(shù)組操作方法
map() 方法
map方法可以分別處理數(shù)組中的成員,返回一個新數(shù)組,也可以用于遍歷數(shù)組文章來源:http://www.zghlxwxcb.cn/news/detail-714617.html
let aList = [1,2,3];
aList.map(function(a){
alert(a);
})
// 彈出 1 2 3
concat() 方法
concat() 方法用于連接新的數(shù)組成員或者其他數(shù)組,返回一個新的數(shù)組文章來源地址http://www.zghlxwxcb.cn/news/detail-714617.html
let aList01 = [1,2,3];
let aList02 = ['a','b'];
let aList03 = arr.concat(4,5);
let aList04 = aList01.concat(aList02);
console.log(aList03) // [1,2,3,4,5]
console.log(aList04) // [1,2,3,'a','b']
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var aList = ['a','b','c'];
//第一個參數(shù)數(shù)組成員值,第二個參數(shù)是成員的索引值
aList.map((item,i)=>{
console.log(item+" | "+i);
})
//concat會返回一個新的數(shù)組
var aList2 = aList.concat('d','f');
var aList3 = [1,2];
var aList4 = aList.concat(aList3);
console.log(aList2);
console.log(aList4);
</script>
</head>
<body>
</body>
</html>
到了這里,關(guān)于ES語法以及ajax相關(guān)操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!