jquery - jquery post 和 html form post 的区别

标签 jquery html node.js express

我搜索了一段时间,但我不明白:

Jquery $.post 和我提交带有 post 的普通 html 表单有什么不同?

我的 jquery 代码:

$.post( "/test", query , function( data ) {
  console.log(data)  
});

我的 html 代码:

<form method="post" action="/test"   >
<input id="query" type="text"  name="q"  >
<input type="submit" value="Search">
</form>

我使用 express,当我执行 jquery post 时,下面的代码将无法工作。服务器只会将重定向作为数据发送,不会重定向页面。但是当我使用表单时,它将重定向页面 tp/newpage。为什么会这样?有没有办法让 jquery 像 html 表单一样工作?

router.post('/test', function(req, res) {
res.redirect('/newpage');
}

我看到在 chrome 中可以看到 jquery 使用类型“xhr”并且表单使用“document”...我可以更改它吗?

最佳答案

What is the different between a Jquery $.post and when i submit a normal html form with post?

在大多数情况下,什么都没有。两者都使用表单中的值发出 HTTP POST 请求。一个只是在页面的上下文中这样做,另一个在 AJAX 上下文中这样做而不刷新页面。

The sever will just send the redirect as data and will not redirect the page.

你这边有点误会。服务器从不 重定向浏览器。服务器所做的只是将 header 发送回浏览器,建议浏览器执行重定向。

当浏览器在页面加载请求的上下文中收到该 header 时,它会执行重定向。当 JavaScript 代码在 AJAX 请求的上下文中接收到该 header 时,它会忽略它。根据设计,AJAX 响应不会重新加载页面。

如果您希望表单发布导致服务器启动的重定向,请使用普通表单 POST。您仍然可以从 JavaScript 启动此表单 POST,只是不使用 $.post() 因为那是一个 AJAX 请求。相反,您可以执行类似 $('form').submit()$('form input[type="submit"]').click() .这可能需要一些修补。

另一方面,如果您想使用 AJAX,那么响应 AJAX 请求完成的任何条件重定向逻辑都需要在客户端逻辑中。

关于jquery - jquery post 和 html form post 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30696574/

相关文章:

jquery - 使用 css sprites 资源图片

jQuery 在动画后重置位置

html - 如何调整两个div的偏移量?

javascript - Discord.js 检测多个 channel 删除和多个禁止

node.js - 如何从 Windows NodeJS 进程运行多个 WSL 命令?

javascript - Passport 和 Mongoose 的 bcrypt 错误

jquery - FOSJsRoutingBundle : Cannot Generate routing url inside javascript

javascript - 如何在浏览器打开新标签页时捕获目标网址

php - 在屏幕上显示用户的用户名。出现 'Undefined Index' 错误

html - Bootstrap 3 列内的相对 div 不受尊重