【发布时间】:2014-11-25 08:10:41
【问题描述】:
我在从 localhost 对 GitHub 域进行 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。
注意:
- 我正在寻找 Pure JS 解决方案。我知道怎么做 jQuery。
- 我实际上并不希望提交表单,只希望提交
应该触发
onSubmit事件。
这是我的JSFiddle
【问题讨论】:
标签: javascript html ajax xmlhttprequest