鍍金池/ 問答/HTML/ 異步ajax如何獲取返回值?

異步ajax如何獲取返回值?

異步ajax設置返回值因為是異步 所以沒獲取到值就會返回
接收到的往往是undefined
那么把異步改成同步以外
有沒有什么方法可以獲取異步的ajax
我本來的思路是接受函數(shù)給個async 然后調用語句加awiat
但是獲取的是promise之類的東西
并沒有獲取到數(shù)據(jù)
異步怎樣獲取返回值呢?
在不使用框架的情況下 原生js有沒有辦法解決?

回答
編輯回答
骨殘心

Axios 是一個基于 promise 的 HTTP 庫,可以看看 : https://github.com/axios/axios

例子:

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// Make a postrequest
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
2018年2月7日 22:45
編輯回答
久不遇

閉包

function a1(data){
    console.log(data)
}
$.ajax().done(function(data){
    a1(data)
})

可以用es6的Generator改造promise為同步 co.js就是這樣做的 co簡寫:

function co(generator) {
  return function(fn) {
    var gen = generator();
    function next(err, result) {
        if(err){
            return fn(err);
        }
        var step = gen.next(result);
        if (!step.done) {
            step.value(next);
        } else {
            fn(null, step.value);
        }
    }
    next();
   }
}
co(function * () {
    var data= yield $.ajax('a.json');
    //同步寫法
    console.log(data);
})
2017年11月18日 23:35