ajax非同步傳輸資料,return返回為undefined
阿新 • • 發佈:2019-02-13
function checkSelectInstance() { var instance; $.ajax({ type: "POST", cache: false, data: "", url: "/ecs/describeInstances", success: function(res) { instance= res; }, error: function(data) { instance= ""; } }); return instance; }
問題:呼叫這個方法後卻返回undefined,
原因:jq的ajax是非同步請求的,所以大多時候還沒有執行完ajax就return了
解決方法:新增async:false,改為同步請求就ok了
function checkSelectInstance() { var instance; $.ajax({ type: "POST", cache: false, data: "", async:false, url: "/ecs/describeInstances", success: function(res) { instance= res; }, error: function(data) { instance= ""; } }); return instance; }