我在從本地主機向GitHub域進行XHR調用時遇到問題。使用普通JavaScript進行XHR調用
一旦點擊按鈕Click to get User Profile with Ajax+JS
,JS函數getUser()
被調用。代碼按預期工作,即獲取特定的GitHub用戶詳細信息(全名和頭像)並顯示在頁面上。
## Code for "Click to get User Profile with Ajax+JS" button
<input type="button" value="Click to get User Profile with Ajax+JS" onclick="getUser()" id="jsBtn" />
但是,當我請使用submit
按鈕表單提交相同的JS函數(或返回),它不返回預期的結果,即,用戶詳細信息。
## Code for "Submit" button
<form id="myForm" onsubmit="getUser()">
#...
<input type="submit"/>
</form>
在Network
下檢查,我看到的是形成在請求的頭部部分中的方式請求URL的區別:
## With GitHub username input as kirtithorat
## First Case With "Click to get User Profile with Ajax+JS" button
Request URL:https://api.github.com/users/kirtithorat
## Second Case With "submit" button
Request URL:http://localhost:3000/html_file_name?username=kirtithorat
爲什麼行爲的差異?相同的JS函數適用於onclick,但不適用於onsubmit。
注:
- 我要尋找一個純JS解決方案。我知道如何在 jQuery中做到這一點。
- 我實際上並不想要提交表單,只有觸發事件的應該是
onSubmit
。
這裏是我的JSFiddle
爲了使編碼更加清晰,我寧願'event.preventDefault()'返回false。防止默認提交是你想要發生的事情,雖然'return false'可能會實現這一點,但這是一種副作用,而不是直接意圖的效果。 – user1167442 2014-11-24 23:57:17
@ jfriend00感謝您的回覆。我在代碼中使用了'return false',但沒有運氣。它的請求URL:http:// localhost:3000/html_file_name?username = kirtithorat' – 2014-11-24 23:57:25
@ user1167442 - 如果這不適合你,那麼你沒有正確阻止提交表單。你的'getUser()'函數甚至無法創建該URL(不同的域,不同的URL),而第二個URL完全匹配通過GET完成的表單提交。所以,問題是如何正確阻止表單提交。 jsFiddle中的'getUser()'代碼在函數返回的任何地方都沒有'return false'。 – jfriend00 2014-11-25 00:02:04