为什么我的jquery ajax POST函数将我的表单数据发送到我的基本URL而不是我指定的url?

时间:2016-04-29 06:42:26

标签: jquery ajax node.js forms post

我有一个表单,我想 POST 数据到我的后端。 在提交表单时,我已成功阻止自己被重定向。我希望POST请求转到MYBASEURL/form

下面的代码几乎可以正常工作,但是Ajax调用似乎忽略了我指定的URL,并向MYBASEURL发出了POST请求。

我正在使用的是什么:

的jquery-1.12.3.min.js

Node.js v4.3.2

Express 4.x

bodyparser

<form name="myform" action="#" method="POST">
  Username: <input type="text" id="user" name="username"/><br/>
  Password: <input type="text" id="email" name="email"/>
  <input type="submit" id="submitForm" value="submit"/>
</form>

<script type="text/javascript">
  var user=$('#user').val(), email=$('#email').val();
  $('#submitForm').bind('click', function() {
    $.ajax({
      url: "/form",
      type: 'POST',
      contentType: 'text/json',
      data: JSON.stringify({name:user, email:email}),
      complete: function() { /* Do something with the response. */ }
    });
    return false; // Prevent form submit.
  });
</script>

将相对网址更改为绝对网址不会改变任何内容。 从操作中删除“#”不会改变任何内容。

如何确保此POST转到MYBASEURL/form/,而不仅仅是MYBASEURL/

2 个答案:

答案 0 :(得分:1)

我认为您的问题不在此代码中。解决了您发布的代码中的错误(设置&#39;用户&#39; var但提交&#39;用户名&#39;和$(&#39; #subitForm&#39;)。bind而不是$ (&#39;#submitForm&#39;)。bind),它运行正常。我想知道你是否通过.htaccess或其他方式发生某种路由。

答案 1 :(得分:0)

只是添加我自己的答案,因为我的前端和后端都有问题:

首先,变量没有在正确的范围内初始化,我的脚本应该是这样的:

<script type="text/javascript">
  $('#submitForm').bind('click', function() {
    var user=$('#user').val(), email=$('#email').val();
    $.ajax({
      url: "/api/users",
      type: 'POST',
      contentType: 'application/json',
      data: JSON.stringify({name: user, email: email}),
      complete: function() { 
        // Do something with the response.
      }
    });

    return false; // Prevent form submit.
  });
</script>

这使我的$.ajax POST能够正确发送到正确的路径:MYBASEURL/form

我的第二个问题是理解我必须设置我的后端才能正确解析与此ajax调用中指定的类型匹配的内容类型。