Javascript 为什么异步ajax请求不';不行?
我是javascript新手。我正在使用此脚本在api中进行身份验证:Javascript 为什么异步ajax请求不';不行?,javascript,jquery,html,ajax,asynchronous,Javascript,Jquery,Html,Ajax,Asynchronous,我是javascript新手。我正在使用此脚本在api中进行身份验证: function try_login() { $.ajax({ type: "POST", url: "http://some.api/auth", dataType: 'json', async: false, data: { username: document.getElementById('username
function try_login() {
$.ajax({
type: "POST",
url: "http://some.api/auth",
dataType: 'json',
async: false,
data: {
username: document.getElementById('username').value,
password: document.getElementById('password').value
},
success: function (data)
{
// alert(data.jwt_token);
window.sessionStorage.setItem('token', data.jwt_token);
// alert(window.location);
window.location.replace("/index.html");
// alert(window.location);
return false;
}
// success: successLogin,
});
}
这是我的html(我也在使用引导):
还尝试设置非相对路径“www.mysite.com/index.html”
Chrome警告说同步请求已被弃用,但正如您所看到的,我的第一个问题是我不知道如何使用异步请求。
而且,这看起来很神奇,但如果我在success函数中取消所有allert的注释,firefox会将我重定向到“index.html”
请帮帮我
首先,为什么我要在true上更改async或删除它(因为在ajax中默认为async true),它不会向api发送post请求,它只会刷新页面
因为您要提交一个表单,这涉及到撕毁页面并取消任何正在进行的ajax请求
其次,当我使用异步false post请求时,它向api发出正常请求并接收正常响应。将令牌保存在sessionStorage中效果很好,但window.location.replace不会在下一页重定向
因为你正在提交一份表格。success
回调中的return false
对表单的submit
事件没有任何影响。如果要防止表单在success
处理程序中提交,请将try\u login
与jQuery挂钩(而不是onclick
属性),接受事件对象,并对其使用preventDefault()
在我看来,你从来没有真正想要提交表单,而只是想用它来触发ajax。如果是这样的话,就没有必要让ajax同步(这也是不同步的好理由): 取下
onclick
,然后按如下方式将其连接起来:
$("any-css-selector-for-the-form").on("submit", try_login);
您可能需要显示一些内容,以表明请求正在进行。您是否希望提交该表单?或者它纯粹是通过ajax运行的?谢谢您的回答!我想通过post请求将输入文本框中的凭证发送到api并接收响应,我不知道在没有ajax的情况下如何处理响应。我试过你的代码,但我不明白在哪里可以连接它。我正在尝试:$(“#表单登录”)。在(“提交”上,尝试登录()),当我访问该站点时,尝试登录函数在每次刷新中都会工作。对不起,如果我问了一些愚蠢的问题,我是JavaScripto的新手哦,天哪,我忘了“#”是id和字符“.”是用来上课的!现在它的工作真棒,谢谢你!!
window.location = "/index.html"
window.location.href = "/index.html"
function try_login() {
$.ajax({
type: "POST",
url: "http://some.api/auth",
dataType: 'json',
data: {
username: document.getElementById('username').value,
password: document.getElementById('password').value
},
success: function(data) {
window.sessionStorage.setItem('token', data.jwt_token);
window.location.replace("/index.html");
}
});
return false;
}
$("any-css-selector-for-the-form").on("submit", try_login);