简体   繁体   English

为什么这个 AJAX 调用不重定向到`/login` URL?

[英]Why does this AJAX call not redirect to the `/login` URL?

I am making a Node Express app with Handlebars.我正在使用 Handlebars 制作 Node Express 应用程序。

I get a success message printed in the console but the URL is not changed to /login , and hence the page never gets rendered, although, when I manually type the URL localhost:3000/login into the browser, I can see my login page rendered.我在控制台中打印了一条成功消息,但 URL 没有更改为/login ,因此页面永远不会被渲染,但是,当我手动输入 URL localhost:3000/login进入浏览器时,我可以看到我的登录页面呈现。

Therefore, I wanted to know why the AJAX is not working.因此,我想知道为什么 AJAX 不工作。

index.handlebars : index.handlebars

<a class="btn" id="login" target="login">Login</a>

login.handlebars : login.handlebars

<input placeholder="Email" name="email" id="email" type="text">
<input placeholder="Password" name="password" id="password" type="password">

index.js : index.js

const baseUrl = 'http://localhost:3000';

$("a[id='login']").click(function(){
  $.ajax({
    url: `${baseUrl}/login`,
    method: 'GET',
    success(){
      console.log('success');
    },
    error(e){
      console.log(e);
    }
  });
});

routes file:路线文件:

router.get('/login', function(req, res)=>{
  try{
    res.render('login');
  }
  catch(e){
    res.status(401).json({
      message: 'Failed'
    });
  }
});

An Ajax call just sends a request to your server and gets the response back to your Javascript. Ajax 调用只是向您的服务器发送一个请求并将响应返回给您的 Javascript。 It does not, by itself, change ANYTHING in the browser window.它本身不会更改浏览器 window 中的任何内容。 If you want to go to the /login page after your ajax call, then you can tell the browser to go to /login by setting window.location = "/login" in your browser Javascript. If you want to go to the /login page after your ajax call, then you can tell the browser to go to /login by setting window.location = "/login" in your browser Javascript.

But, what it looks like you really want to do is to just change the window location instead of even using the ajax call since the Ajax call by itself isn't doing anything except render a login form.但是,看起来您真正想要做的只是更改 window 位置,而不是使用 ajax 调用,因为 Ajax 调用本身除了渲染登录之外没有做任何事情。

const baseUrl = 'http://localhost:3000';

$("a[id='login']").click(function(){
      // now render the login page
      window.location = "/login";
   });
});

But, since all this is doing is sending the browser to a new web page, you don't even need Javascript for this, you would just use an <a href="/login">Login<a> in your page too.但是,由于所有这些都是将浏览器发送到新的 web 页面,因此您甚至不需要 Javascript ,您只需在页面中使用<a href="/login">Login<a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM