Ajax同步、异步和相应数据格式

(一)同步和异步

xhr.open()方法第三个参数要求传入的是一个 布尔值,其作用就是设置此次请求是否采用异步方式执行

默认为 true异步

可修改为 false为同步。

异步代码举栗:

 1 console.log(‘before ajax‘) 2 var xhr = new XMLHttpRequest() 3 // 默认第三个参数为 true 意味着采用异步方式执行 4 xhr.open(‘GET‘, ‘/time‘, true) 5 xhr.send(null) 6 xhr.onreadystatechange = function () { 7 if (this.readyState === 4) { 8 // 这里的代码最后执行 9 console.log(‘request done‘)10  }11 }12 console.log(‘after ajax‘)13 //输出结果:14 //before ajax15 //after ajax16 //request done

 

如果采用同步方式执行,则代码会卡死在 xhr.send() 这一步:

同步代码举栗:

 1 console.log(‘before ajax‘) 2 var xhr = new XMLHttpRequest() 3 // 同步方式 4 xhr.open(‘GET‘, ‘/time‘, false) 5 // // 同步方式 执行需要 先注册事件再调用 send,否则 readystatechange 无法触发 6 xhr.onreadystatechange = function () { 7 if (this.readyState === 4) { 8 // 会按代码执行顺序执行这行代码 9 console.log(‘request done‘)10  }11  }12 xhr.send(null)13 // 因为 send 方法执行完成 响应已经下载完成14 console.log(xhr.responseText)15 console.log(‘after ajax‘)16 //输出结果:17 //before ajax18 //request done19 //155843714457220 //after ajax
 

(二)响应数据格式

1. JSON

JSON的本质是字符串。

  • JSON 中属性名称必须用双引号包裹
  • JSON 中表述字符串(值)必须使用双引号
  • JSON 中不能有单行或多行注释
  • JSON 没有 undefined 这个值
  • 一个完整的JSON,不能有其他内容掺杂

数据类型:null,number,boolean,string,object,array

2. 数据转换

JSON转JS:JS = JSON.parse(JSON)

JS转JSON:JSON = JSON.stringify(JS);

代码举栗:

 1 // JS数据和JSON数据相互转换 2 // 先定义一些JS数据 3 var js_b = true; 4 var js_o = {name: ‘zs‘, age: 20, sex: ‘M‘}; 5 var js_a = [‘red‘, ‘green‘, ‘blue‘]; 6  7  console.log(js_b); 8  console.log(js_o); 9  console.log(js_a);10 11 // 1. JS数据转换成JSON格式12 var json_b = JSON.stringify(js_b);13 var json_o = JSON.stringify(js_o);14 var json_a = JSON.stringify(js_a);15 16  console.log(json_b);17  console.log(json_o);18  console.log(json_a);19 20 // 2. 把JSON数据转换成JS数据21  console.log(JSON.parse(json_b));22  console.log(JSON.parse(json_o));23 console.log(JSON.parse(json_a));

 

 

相关文章