iT邦幫忙

0

我在練習javascript的Ajax,我用axios出現問題,不知道該怎麼解決?

  • 分享至 

  • xImage

各位大大好!我在練習Javascript中ajax的axios,我把程式碼和json檔放在同一個資料夾,沒有放在server端,在vscode撰寫程式碼,但我貼上axios的cdn後,用go live執行,google chrome上渲染,結果出現錯誤,該怎麼辦呢?Json檔案格式錯誤嗎?
/images/emoticon/emoticon02.gif/images/emoticon/emoticon04.gif

vscode編輯器上照片:
https://ithelp.ithome.com.tw/upload/images/20230630/201459923Mwpf4Q1Tj.png

google chrome上渲染照片:
https://ithelp.ithome.com.tw/upload/images/20230630/20145992pBOgWTIahW.png

檔案夾照片:
https://ithelp.ithome.com.tw/upload/images/20230630/20145992ta5huXQtJw.png

json檔案如下:

[
	{
		"name":"David",
		"age":"27",
		"chin":"83",
		"eng":"76",
		"math":"91"
	},
	{
		"name":"Amy",
		"age":"18",
		"chin":"77",
		"eng":"93",
		"math":"65"
	}
]

程式碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascrip ajax Axios get 1</title>
    <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.4.0/axios.min.js" integrity="sha512-uMtXmF28A2Ab/JJO2t/vYhlaa/3ahUOgj1Zf27M5rOo8/+fcTUVH0/E0ll68njmjrLqOBjXM3V9NiPFL5ywWPQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>-->
    <!--<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>-->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>

    <button onclick="show();">連線取得資料</button>
	<div id="result"></div>
	<script>

		function show() {
            
               
                axios.get("/json/student.json").then(function(response){
                    let result=document.querySelector("#result");
                    for(let i=0;i<data.length;i++){
                        let stu=data[i];
                        result.innerHTML+="學生姓名:"+stu.name+
                                        "<br>學生年齡:"+stu.age+
                                        "<br>國文成績:"+stu.chin+
                                        "<br>英文成績:"+stu.eng+
                                        "<br>數學成績:"+stu.math+"<br>";
                    }
                });
            
		}
		
	</script>
</body>
</html>

錯誤訊息如下:

Live reload enabled.
jquery-3.4.1.min.js:2 Error: <path> attribute d: Expected number, "…               tc0.2,0,0.4-0.2,0…".
xe @ jquery-3.4.1.min.js:2
content.js:1 Uncaught DOMException: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index.
    at Content.isSelection (chrome-extension://bebmphofpgkhclocdbgomhnjcpelbenh/scripts/content.js:1:18131)
    at Content.handleSelection (chrome-extension://bebmphofpgkhclocdbgomhnjcpelbenh/scripts/content.js:1:17817)
axios1.html:22 Uncaught (in promise) ReferenceError: data is not defined
    at axios1.html:22:35
DevTools failed to load source map: Could not load content for chrome-extension://mnlohknjofogcljbcknkakphddjpijak/js/lib/purify.min.js.map: System error: net::ERR_BLOCKED_BY_CLIENT
DevTools failed to load source map: Could not load content for chrome-extension://cofdbpoegempjloogbagkncekinflcnj/build/content.js.map: System error: net::ERR_BLOCKED_BY_CLIENT
看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2023-06-30 23:16:59 檢舉
前面兩個有點莫名奇妙,都是jQuery的問題,但axios 是沒用到的
最後一個是你寫錯了,data 這個變數你有定義過嗎?

另外學著看debug
好的,我去定義data變數,謝謝妳,因為我沒看過哪些debug,所以才請教各位大大。
greenriver iT邦研究生 5 級 ‧ 2023-07-03 08:39:15 檢舉
首先,要先定義data。
像rain_yu大大說的那樣,let data=response.data。
因為這是axios本身定義的,會將收到的資料放到response.data裡。
ps. 雖然不影響axios的結果,但你的json格式是錯的。
要像這樣:
{
"data":[....]
}
謝謝妳!
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
rain_yu
iT邦新手 1 級 ‧ 2023-07-03 08:19:29

要正確地發送AJAX,你可以按照以下步驟進行修改:

  1. 調整script標籤中引入的axios庫的路徑,目前使用的是unpkg的CDN,可以確保庫的正確加載,如果你想使用本地庫,可以將路徑修改為庫的本地路徑。

  2. 將axios.get的URL引號括起來。目前的代碼中,URL沒有被引號括起來,這會導致語法錯誤。你可以將URL修改為字串,例如axios.get('/json/student.json')。

  3. 在then方法中,將response.data賦值給data變量。在之前的代碼中,data變量並沒有被定義,這導致循環無法運行。你可以將axios.get的回調函數修改為function(response),然後將response.data賦值給data變量,例如let data=response.data。

  4. 在循環中,將stu變量改為response.data[i],這樣才能正確地訪問每個學生的屬性。

  5. 在innerHTML中,將+號前後的字符串用引號括起來,例如'學生姓名:'+stu.name+''。

修改後的代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascrip ajax Axios get 1</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>

    <button onclick="show();">連線取得資料</button>
    <div id="result"></div>
    <script>

        function show() {
            axios.get('/json/student.json').then(function(response){
                let result=document.querySelector('#result');
                let data=response.data;
                for(let i=0;i<data.length;i++){
                    let stu=data[i];
                    result.innerHTML+="學生姓名:"+stu.name+"<br>"+
                                    "學生年齡:"+stu.age+"<br>"+
                                    "國文成績:"+stu.chin+"<br>"+
                                    "英文成績:"+stu.eng+"<br>"+
                                    "數學成績:"+stu.math+"<br>";
                }
            });
        }

    </script>
</body>
</html>

謝謝妳!大大

我要發表回答

立即登入回答