【问题标题】:Ajax function not being called on form submit表单提交时未调用 Ajax 函数
【发布时间】:2017-06-07 09:19:50
【问题描述】:

我是这方面的初学者,如果我只是愚蠢,请原谅。

所以基本上我试图让一个 div 在使用 ajax 提交表单后重新加载来自 php 文件的信息,这就是我所拥有的。

index.php

<script type="text/javascript">
$('#searchForm').submit(function(event){
  $.ajax({
    url: 'result.php',
    type: 'post',
    dataType:'html',   //expect return data as html from server
    data: $('#searchForm').serialize(),
    success: function(response, textStatus, jqXHR){
      $('#underInput').html(response);
     },
  error: function(jqXHR, textStatus, errorThrown){
  console.log('error(s):'+textStatus, errorThrown);
  }
 });
 });
</script>

    <form class="form-group" id="searchForm" onsubmit="return false">
        <div class="input-group">
            <input id="search" class="form-control" name="user" type="text" placeholder="Enter instagram username">
            <span class="input-group-btn">
            <button class="btn btn-primary" id="submit" type="submit">Sök</button>
            </span>
        </div>
    </form>
        <div id="underInput"/>

结果.php

//dont want to show calculation for therate here
echo '<h2><?php echo $_POST["user"]?> can charge <?php echo $therate?>€ per 
post</h2>';    

当我点击提交时没有任何反应,为什么?

【问题讨论】:

  • 删除表单标签中的 onsubmit="return false"
  • 为什么你有这个属性 onsubmit="return false"
  • 您的代码正在运行...检查控制台是否有任何错误?
  • 你的代码中是否包含了 jQuery 库?
  • 什么都没有发生,因为你写了 "onsubmit="return false" " 。删除那个

标签: javascript php ajax forms


【解决方案1】:

点击而不是提交时使用

示例-

 $(document).ready(function(){
    $('#submit').on("click", function(event){
      $.ajax({
        url: 'result.php',
        type: 'post',
        dataType:'html',   //expect return data as html from server
        data: $('#searchForm').serialize(),
        success: function(response, textStatus, jqXHR){
          $('#underInput').html(response);
         },
      error: function(jqXHR, textStatus, errorThrown){
      console.log('error(s):'+textStatus, errorThrown);
      }
     });
     });
});

然后用这段代码替换你的php代码

<?php
echo '<h2>'.$_POST["user"].' can charge '.$therate.' € per 
post</h2>'; 
?>

【讨论】:

  • 呃,仍然没有任何反应:/。我也在 标签中包含了这个:
  • 尝试提醒一些东西,如果它的警报然后告诉我例子 $('#submit').on("click", function(event){ alert("hello"); });跨度>
  • 即使我使用 $('#searchForm').submit(function(event) 也没有。在控制台中没有收到任何警报或消息。
  • 好的,看看我更新的答案。我添加了文档就绪代码,将其更新到您的代码中并检查。
  • 是的,如果我在 $('#underInput').html(response); 之前添加警报。它确实出现了。但是 div 仍然没有改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
相关资源
最近更新 更多