javascript - 如何等到 ajax 函数在 javascript 中完成
问题描述
我有两个功能。ajax 函数的一个函数调用。我的问题是它没有等到 ajax 函数完成。它之前正在执行我的其他代码。如何等待ajax完成?
function getdata(){
var imgPath = getImgPath();
const img2 = document.getElementById("backimg");
img.src = imgPath;
}
function getImgPath(){
$.ajax({
url:spath,
type:'HEAD',
dataType: "jsonp",
crossDomain: true,
secure: true,
// async:false,
headers: {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
},
success: function()
{
//file exists do something here
console.log("exist ");
path = spath;
},
error: function()
{
//file does not exist
console.log("doesnt exist");
path = lpath;
}
});
}
这是我尝试过的。这个 ajax 函数执行得很好,但是当我在完成 getImgPath() 函数之前运行我的代码时,它正在执行其他代码行。我怎样才能等到ajax函数完成?
解决方案
推荐阅读
- wordpress - 在 Wordpress 仪表板中编辑帖子时如何折叠子类别
- google-analytics - 谷歌分析 4 事件参数?
- python - 当 `powsimp` 和 `collect` 都什么都不做时, `simplify` 应用什么转换?
- three.js - 从 CatmullRomCurve3 和 ExtrudeBufferGeometry 更新路径
- python - 如何使用python客户端api从GCS云存储桶下载文件夹中的所有文件?
- react-table - 使用 React 表编辑特定列
- python - 如何使用 Pandas 操作包含列表的列以删除非常相似的元素?
- mysql - MySQL 连接/联合
- python - 访问嵌套键中的每个键
- c++ - 多个模板的笛卡尔积