aszx87410 / frontend-intermediate-course

It's a free online course about some frontend tech including Ajax, CORS, gulp, webpack and so on.
266 stars 88 forks source link

[作業] 繳交hw6 #100

Closed pychiang closed 7 years ago

pychiang commented 7 years ago

slack 帳號

pychiang

哪一個作業

  1. 返璞歸真:vanilla js

作業 Github 連結

https://github.com/pychiang/frontend-intermediate-course/tree/master/answers/hw6

作業 Github Page 連結

https://pychiang.github.io/frontend-intermediate-course/answers/hw6/index.html

其他補充說明

  1. 參考了 ponponwu 同學的 JS 寫法,太感謝了!
  2. 在 DevTools 的 Console 裡會看到 "Uncaught ReferenceError: err is not defined at XMLHttpRequest.request.onreadystatechange" 這一段錯誤碼,但我不知道應該怎麼修正。是要事先宣告 err 這個變數再代入變參數嗎?還是 callback function 有專門處理錯誤訊息的參數,但是在 callback function 的第一個參數不通常是表示 error 的嗎?(其實我也不太確定那一段 error handling 寫得對不對 XD)
aszx87410 commented 7 years ago

你看一下上次作業的這一段:https://github.com/pychiang/frontend-intermediate-course/blob/master/answers/hw5/JS/script.js#L25-L27

error: function(err) {
        $container.append('<div class="error">Failed to Load Twitch Data.</div>');
}

這邊的 err$.ajax 幫你傳進來的錯誤參數

可是當這次改寫成 vanilla js 的時候,你會發現你沒有err這個東西可以拿了 為什麼?因為它沒有給你,所以你這一段:

request.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
        var response = JSON.parse(this.responseText);
        callBack(null, response);
    } else {
        callBack(err);
    }
}

他才會出這個錯誤:Uncaught ReferenceError: err is not defined at XMLHttpRequest.request.onreadystatechange,意思就是 err 這個變數沒有宣告,也找不到這東西在哪 要改掉的話,你可以自己建一個 Error 出來,或是傳一個字串其實也可以

request.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
        var response = JSON.parse(this.responseText);
        callBack(null, response);
    } else {
        callBack(new Error('xhr not ready or status not equal to 200'));
    }
}
pychiang commented 7 years ago

原來如此!太感謝了!