简单的.ajax失败

时间:2017-02-28 09:05:24

标签: jquery

.ajax失败的简单小提琴:

=

和welcome_post.php回复

<form action="welcome_post.php" method="post" id="f">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
<script>
  $(document).ready(function(){
      $("#f").submit(function(event) {
          event.preventDefault();
          $.post("/tests/welcome_post.php",function(data){
              alert(data)
          }); 
      }); 
  });
</script>

如果我删除了event.preventDefault(),代码会加载一个新的php页面并运行,否则$ _POST变量没有设置,并且警报带有未定义的索引错误。如何设置.post工作?

2 个答案:

答案 0 :(得分:0)

它不起作用,因为你实际上没有发送POST数据。

这应该有效:

jQuery('#f').submit(function(evt) {
    evt.preventDefault();
    var data = jQuery(this).serialize();
    jQuery.post('your/url.php', data, function(result) {
        console.log(result);
    });
});

答案 1 :(得分:0)

您没有在请求中发送任何数据。因为它是ajax,你必须告诉它使用什么数据。它不会自动使用表单数据,您必须指定它:

else

有关您可以使用此方法提交的参数的完整列表,请参阅https://api.jquery.com/jquery.post/

此外,您应该使用浏览器的“开发人员工具”的“网络”标签来监控请求和响应的内容 - 这有助于您了解此类问题的根本原因。

相关问题