嘗試使用 when 呼叫從 ajax 呼叫中將 ajax 資料檢索到 jquery 中的變數。但據我了解,資料是未完成的 ajax 資料。在下面我無法訪問 responseJSON 下的資料時以物件形式給出回應。
{readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function, …}
//jQuery代碼用ajax呼叫函式
jQuery(document).ready(function() {
var response = ajaxcall();
console.log(response);
});
//功能
function ajaxcall(){
return $.ajax({
url: "url",
type: "POST",
data: form_data,
dataType: 'json',
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
},
success: function(data)
{
if(data=='invalid')
{
alert("invalid data");
}
else
{
// success
return data;
}
},
error: function(e)
{
}
});
}
uj5u.com熱心網友回復:
是的,因為 ajax 呼叫是異步的。所以你必須傳遞一個回呼函式或者使用promise或者使用 jquery.when
1.使用$ .when
$(document).ready(function() {
$.when(ajaxcall()).then(response=>{
console.log(response)
})
});
function ajaxcall(callback){
return $.ajax({
url: "https://jsonplaceholder.typicode.com/users/1",
type: "GET",
dataType: 'json'
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2.將回呼函式作為ajaxCall的引數傳遞
$(document).ready(function() {
var response = ajaxcall((response)=>{
console.log(response);
});
});
function ajaxcall(callback){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users/1",
type: "GET",
dataType: 'json',
success: function(data){
callback(data)
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
3.使用承諾
$(document).ready(function() {
var response = ajaxcall().then(response=>{
console.log(response)
})
});
function ajaxcall(callback){
return new Promise((resolve, reject) => {
$.ajax({
url: "https://jsonplaceholder.typicode.com/users/1",
type: "GET",
dataType: 'json',
success: function(data){
// success
resolve(data)
},
error: function(e){
reject(e)
}
});
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
注意:在上面的示例中,我稍微修改了您的示例查詢以使其在代碼段中作業。
因此,在您的情況下,您必須重新添加標頭引數
url: "url",
type: "POST",
data: form_data,
dataType: 'json',
contentType: false,
cache: false,
processData:false,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/486035.html
