iT邦幫忙

1

ajax 抓取JSON資料轉成陣列的問題

  • 分享至 

  • xImage
    $.ajax({
        url: "http://localhost/TGOS/TgosPoint.json",
        type: "GET",
        dataType: "json",
        success: function(data) {
           for (var i =0 ; i < data.length; i++) {
                Point[i] = data[i].x + ',' + data[i].y               
            }
            console.log(Point[0])
        },
        error: function(data) {
            console.log("error");
        }
    })
    console.log(Point)
    console.log(Point[0])

請問這樣寫的語法哪裡有問題,因為本身目前對javascript還不太熟
https://ithelp.ithome.com.tw/upload/images/20220612/20149121k2f0LZ9eQD.png
這樣去顯示陣列的資料是正確的嗎?因為console.log(Point[0])是undefined
但是如果寫在ajax的框架裡面console.log(Point[0])卻抓的到資料

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
Zero皇
iT邦研究生 3 級 ‧ 2022-06-12 20:06:00

可以試著去研究這篇:JavaScript Promise 全介紹,這是因為ajax是異步方法,他會等下面其他程式(不是異步的)執行完才執行
所以真正的資料會等到33行跟34行的console.log都執行完,才會取得
所以寫在ajax的success裡的方法的console.log(Point[0])才有辦法顯示。

jiun917 iT邦新手 5 級 ‧ 2022-06-13 01:18:46 檢舉

感謝推薦 我再找時間看

0
小魚
iT邦大師 1 級 ‧ 2022-06-12 21:21:55

把你要寫的程式碼寫在success那個function裡面

jiun917 iT邦新手 5 級 ‧ 2022-06-13 01:19:00 檢舉

感謝 已解決

0
超級前端人
iT邦新手 3 級 ‧ 2022-07-09 23:47:29

可以用js新的語法

let res = await fetch("http://url.com")
let data = await res.json()
// now data is javascript not json

就這樣,我覺得非常簡單。記得要放async function在外面。

我要發表回答

立即登入回答