ajax

ajax一个前后台配合的技术,它可以让javascript发送http请求,与后台通信,获取数据和信息。ajax技术的原理是实例化xmlhttp对象,使用此对象与后台通信。jquery将它封装成了一个函数$.ajax(),我们可以直接用这个函数来执行ajax请求。

ajax需要在服务器环境下运行。

$.ajax使用方法 常用参数: 1、url 请求地址 2、type 请求方式,默认是’get’,常用的还有’post’ 3、dataType 设置返回的数据格式,常用的是’json’格式,也可以设置为’text’ 4、data 设置发送给服务器的数据 5、success 设置请求成功后的回调函数 6、error 设置请求失败后的回调函数 7、async 设置是否异步,默认值是’true’,表示异步

以前的写法:

$.ajax({

url: '/change_data',

type: 'get',

dataType: 'json',

data:{'code':300268}

success:function(dat){

alert(dat.name);

},

error:function(){

alert('服务器超时,请重试!');

}

});

新的写法(推荐):

$.ajax({

url: '/change_data',

type: 'get',

dataType: 'json',

data:{'code':300268}

})

.done(function(dat) {

alert(dat.name);

})

.fail(function() {

alert('服务器超时,请重试!');

});

$(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('服务器超时,请重试!');

}

}).done(function(dat){

$('.login_btn').hide();

$('.login_info em').html( dat.name ).parent().show();

}).fail(function(){

alert('服务器超时,请重试!');

})

*/

// 上面是完整写法,可以简写成下面$.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在它的基础上增加了一些语法,ES6是未来JavaScript的趋势,而且React库中大量使用了ES6的语法,所以掌握这些常用的ES6语法是必须的。

变量声明let和const

let和const是新增的声明变量的开头的关键字,在这之前,变量声明是用var关键字,这两个关键字和var的区别是,它们声明的变量没有预解析,let和const的区别是,let声明的是一般变量,const申明的常量,不可修改。

alert(iNum01) // 弹出undefined

// alert(iNum02); 报错,let关键字定义变量没有变量预解析

// alert(iNum03); 报错,const关键字定义变量没有变量预解析

var iNum01 = 6;

// 使用let关键字定义变量

let iNum02 = 12;

// 使用const关键字定义变量

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);

示例

Document

解构赋值

ES6 允许我们按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)

1、数组的解构赋值

const arr = [1, 2, 3]

let [a, b, c] = arr

console.log(a, b, c); // 1 2 3

2、对象的解构赋值

const obj = { name: 'tom',address:'beijing', age: '100'}

let {name, age} = obj // 变量名称必须和对象的key同名

console.log(name, age); //tom 100

3、函数参数的解构赋值

const person = { name: '小明', age: 11}

function printPerson({name, age}) { // 函数参数可以解构一个对象

console.log(`姓名:${name} 年龄:${age}`);

}

printPerson(person) // 姓名:小明 年龄:11

字符串模板

ES6中提供了模版字符串,用`(反引号)标识,用${}将变量括起来

let name = '小明';

let age = 11;

alert(`我的名字是${name},我的年龄是${age}岁。`)

示例

Document

扩展运算符(…)

扩展运算符(…),它用于把一个数组转化为用逗号分隔的参数序列,它常用在不定参数个数时的函数调用,数组合并等情形。

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

示例

Document

箭头函数

可以把箭头函数理解成匿名函数的第二种写法,箭头函数的作用是可以在对象中绑定this,解决了JavaScript中this指定混乱的问题。

// 定义函数的一般方式

/*

function fnRs(a,b){

var rs = a + b;

alert(rs);

}

fnRs(1,2);

*/

// 通过匿名函数赋值来定义函数

/*

var fnRs = function(a,b){

var rs = a + b;

alert(rs);

}

fnRs(1,2);

*/

// 通过箭头函数的写法定义

var fnRs = (a,b)=>{

var rs = a + b;

alert(rs);

}

// fnRs(1,2);

// 一个参数可以省略小括号

var fnRs2 = a =>{

alert(a);

}

fnRs2('haha!');

// 函数中如果只有一个return语句,return和大括号都可以省略

/*

var fnAdd = function(a,b){

return a + b;

}

*/

var fnAdd = (a,b) => a+b;

// 函数的返回值如果是javascript对象时,对象需要加括号

/*

let fn = function(){

return {"a":5};

}

*/

// fn = ()=>{"a":5}

// 上面这么写是错的,需要写成下面的形式,返回的对象要加括号

fn = ()=>({"a":5})

示例

// 箭头函数的作用,可以绑定对象中的this

var person = {

name:'tom',

age:18,

showName:function(){

setTimeout(()=>{

alert(this.name);

},1000)

}

}

person.showName();

模块导入import和导出export

javascript之前是没有模块的功能的,之前做js模块化开发,是用的一些js库来模拟实现的,在ES6中加入了模块的功能,一个js文件就是一个模块,js文件中需要先导出(export)后,才能被其他js文件导入(import)

ES6的导出分为名字导出和默认导出 1、名称导出 导入的变量名必须和导出的变量名一致

// mod01.js文件中导出

export let iNum01 = 12;

export let fnMyalert = function(){

alert('hello');

}

// index.html文件中导入

// mod01.js中还可以写成如下:

let iNum01 = 12;

let fnMyalert = function(){

alert('hello');

}

export {iNum01,fnMyalert}

2、默认导出(default export) 一个模块只能有一个默认导出,对于默认导出,导入的名称可以和导出的名称不一致,这对于导出匿名函数或类非常有用。

// mod02.js文件中导出

export default {"name":"tom","age":18}

// index.html文件中导入

对象的简写 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();

示例

Document

定义类及类的继承

ES6 封装了class语法来大大简化了类的创建和类的继承

// 定义类,类的首字母要大写

class Person {

// 定义构造函数

constructor(name,age){

this.name = name;

this.age = age;

}

// 定义方法

showname(){

alert('我的名字是:' + this.name);

}

showage(){

alert('我的年龄是:' + this.age);

}

}

// 通过类实例化对象

let Andy = new Person('刘德华',55);

// 调用对象的方法

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','北京一中');

// 调用对象的方法

Tom.showname();

Tom.showschool();

示例

Document

异步操作

es6新增了异步操作的写法,来解决异步操作函数回调的问题,这个新增的写法就是Promise对象,Promise实际上就是一个特殊的Javascript对象,反映了”异步操作的最终值”。”Promise”直译过来有预期的意思,因此,它也代表了某种承诺,即无论你异步操作成功与否,这个对象最终都会返回一个值给你。 在实际开发中,如果我们在写ajax程序时,我们如果希望两个ajax程序都执行完后,再去做一件事情,我们实现的方法可以是,在一个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对象来处理回调

pro01.then(function(dat){

console.log(dat);

}).catch(function(err){

console.log(err)

})

上面将两个ajax请求分别放在两个promise对象中,其中resolve参数是处理请求成功的回调函数,reject是处理失败的回调函数,接着就可以通过这个对象,来处理ajax的回调,相当于把回调拆开了写。 如果希望两个ajax程序都执行完后,再去做一件事情,可以写成如下的形式:

Promise.all([pro01,pro02]).then(result=>console.log(result));

示例

Document

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

新增数组操作方法

map() 方法 map方法可以分别处理数组中的成员,返回一个新数组,也可以用于遍历数组

let aList = [1,2,3];

aList.map(function(a){

alert(a);

})

// 弹出 1 2 3

concat() 方法

concat() 方法用于连接新的数组成员或者其他数组,返回一个新的数组

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']

示例

Document

参考链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: