原生ajax

  1. var url = "http://192.168.4.18:8000/"
  2. var xhr = new XMLHttpRequest();
  3. xhr.open("get", url, true);
  4. xhr.send();
  5. xhr.onreadystatechange = function () {
  6. if (xhr.readyState == 4 && xhr.status == 200) {
  7. var result = JSON.parse(xhr.responseText);
  8. console.log(result)
  9. }
  10. }

回调函数去封装ajax

  1. // 需要记住传参的顺序
  2. function ajax(url,method="get",success) {
  3. var xhr = new XMLHttpRequest();
  4. xhr.open(method, url, true);
  5. xhr.send();
  6. xhr.onreadystatechange = function () {
  7. if (xhr.readyState == 4 && xhr.status == 200) {
  8. var result = JSON.parse(xhr.responseText);
  9. success(result)
  10. }
  11. }
  12. }
  1. function ajax({
  2. url,
  3. method="get",
  4. success
  5. }) {
  6. var xhr = new XMLHttpRequest();
  7. xhr.open(method, url, true);
  8. xhr.send();
  9. xhr.onreadystatechange = function () {
  10. if (xhr.readyState == 4 && xhr.status == 200) {
  11. var result = JSON.parse(xhr.responseText);
  12. success(result)
  13. }
  14. }
  15. }

jquery-ajax

  1. $.ajax({
  2. url:"http://192.168.4.18:8000/",
  3. type:"get",
  4. dataType:"json",
  5. success:res=>{
  6. console.log(res)
  7. }
  8. })

callback封装jquery-ajax

  1. function http({url,type="get",success}){
  2. $.ajax({
  3. url,
  4. type,
  5. dataType:"json",
  6. success:res=>{
  7. success(rs)
  8. }
  9. })
  10. }

promise封装ajax

将纵向嵌套的ajax,变成横向的了,结构稍微清晰了一点。

  1. function http(url){
  2. return new Promise((resolve,reject)=>{
  3. $.ajax({
  4. url,
  5. type:"get",
  6. success:res=>{
  7. resolve(res)
  8. },
  9. error:err=>{
  10. reject(err);
  11. }
  12. })
  13. })
  14. }