我对从本地主机到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。
注:
onSubmit事件。这是我的JSFiddle
发布于 2014-11-24 23:47:36
第二个URL看起来像表单提交,而不是调用getUser()的结果( getUser() ajax调用可能就在表单提交之前)。
如果不希望表单实际提交(这似乎是您想要的方式),并且只希望调用onSubmit处理程序,则需要确保防止提交表单的默认行为。
只需添加一个
return false;到getUser() onsubmit处理程序函数的末尾。
或者,可以通过将事件传递到getUser()函数并使用e.preventDefault()来阻止表单提交。
阻止表单提交的另一个原因是页面将重新加载表单提交的结果,而您的javascript将不会仍然活动以接收getUser() ajax调用的结果。因此,您必须使用一个也是唯一一个Ajax调用或表单提交(看起来您只需要ajax调用,这样就可以防止表单提交)。
https://stackoverflow.com/questions/27116280
复制相似问题