使用以下 ajax 函式呼叫以 JSON 格式回傳資料的 API 端點不會將resultsundefined的值json['info']更改async為 .
檢查包含此功能的網頁,它顯示此功能已被棄用,并且不建議任何其他內容。
如何在不撰寫更多代碼來決議從服務器回傳的資料的情況下讀取 json 資料?
function update_info()
{
var results ;
$.ajax({
type: 'GET',
url : "ip:port/api/info",
async:true,
success: function(data) {
results = data['info'];
//console.log(results);
}
});
console.log(results);
return results;
}
這似乎不符合我的目標,因為資料是從 API 回傳的,而不是網頁源代碼回傳到 ajax。
uj5u.com熱心網友回復:
正如大衛所指出的,你應該使用異步呼叫
function update_info()
{
return $.ajax({
type: 'GET',
url : "ip:port/api/info",
async:true,
success: function(data) { data;}
});}
async function f1() {
var results = await update_info();
console.log(results['info']);
}
f1();
這將在完成后回傳 ajax 呼叫,然后您可以從中獲取info資料
uj5u.com熱心網友回復:
您可以同時使用這兩種方法,并且可以使用.then或await。
我附上了以下示例的源代碼。
ajaxRequest("https://httpbin.org/ip").then(result => {
console.log('Your PC Address is:' result.origin);
});
let myPcRes = await ajaxRequest("https://httpbin.org/ip");
console.log('Your PC Address is from the await approach: ' myPcRes.origin);
你需要比較results的$.ajax
并回傳來自成功方法的回應。
我希望你會覺得它有幫助, https://jsfiddle.net/tru5k6qz/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/391532.html
標籤:阿贾克斯
上一篇:加載HTML時的MVC錯誤。具有鍵“MYKEY”的ViewData項的型別為“System.String”,但必須為“IEnumerable<SelectListItem>”型別
