这里为什么里面输出为7,外面输出为0?
怎么能使外面的赋上值?
把Ajax的async改成false,再打印看看
ajax默认是异步的,如果要在外部获取,应该改成同步,即async: false。一般ajax还是直接回调吧,否则失去了使用的意义。
异步数据可以采用Promise来解决
data.json
{
"data": [
{ "name": "张三" },
{ "name": "李四" },
{ "name": "王五" }
]
}
index.html
$(document).ready(function() {
let my_res = []
let myPromise = new Promise((resolve, reject) => {
$.ajax({
url: './data.json',
dataType: 'json',
success: (res) => {
const c = []
for(let n = 0; n < res.data.length; n++) {
c.push({ value: 10, name: res.data[n].name })
}
my_res = c
resolve('') // 处理完后执行方法resolve, resolve是function类型
}
})
})
myPromise.then(() => {
console.log('接口数据:', my_res ) // 处理后的数据
})
})
浏览器运行
要点: 需放服务器上访问, 本地会报跨域问题