首页 > 解决方案 > 如何等到 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函数完成?

标签: javascriptjqueryajax

解决方案


推荐阅读