简体   繁体   English

提交表单而不重新加载页面并获取输出[PHP,jQuery]

[英]Submit Form Without Reloading Page and Get Output [PHP, jQuery]

Hellow, I've been trying to submit a form without reloading and getting PHP output on the same page. Hellow,我一直在尝试提交表单而不重新加载并在同一页面上获取PHP输出。 The main objective is to submit the form values to a PHP file and get the output sent by the PHP file. 主要目标是将表单值提交到PHP文件并获取PHP文件发送的输出。 To understand it better, let's take a look on following code snippet: HTML & jQuery Code: 为了更好地理解它,让我们看看下面的代码片段:HTML和jQuery代码:

<html>
  <head>
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'on.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form>
      <input id="name" name="name"><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

PHP Code: PHP代码:

<?php
if (isset($_POST['submit'])){
$name=$_POST['name'];
if($name == 'Johny'){
    echo "Welcome Johny";
}
else{
echo "I Dont Know You";
}
}
?>

What I Want: 我想要的是:

  • When user enter value in the Input box and submit it, the page should display output value eg ECHO value without reloading the webpage. 当用户在输入框中输入值并提交时,页面应显示输出值,例如ECHO值,而不重新加载网页。

To be more specific on my first comment, you have to put an exit statement after you echo the response so the rest of the code doesn't execute, also to check whether the form was sent or not you can add a hidden input in your form with the value "1" ( <input name="formSent" type="hidden" value="1"> ) that gets checked in your PHP : 为了更具体地说明我的第一个注释,你必须在回显响应后放置一个exit语句,这样代码的其余部分就不会执行,也检查表单是否已发送,你可以在你的内容中添加一个隐藏的输入在PHP中检查值为“1”( <input name="formSent" type="hidden" value="1"> )的<input name="formSent" type="hidden" value="1">

<?php
if (isset($_POST['formSent'])){
$name=$_POST['name'];
if($name == 'Johny'){
  echo "Welcome Johny";
  exit;
}
else{
  echo "I Dont Know You";
  exit;
}
}
?>

and then get the response from the ajax request in the success's callback parameter, also specify the method: 'POST' because jQuery's $.ajax function uses the method GET by default: 然后在success的callback参数中获取ajax请求的响应,同时指定method: 'POST'因为jQuery的$ .ajax函数默认使用GET方法:

<script>
  $(function () {

    $('form').on('submit', function (e) {

      e.preventDefault();

      $.ajax({
        type: 'post',
        url: 'on.php',
        method: 'POST',
        data: $('form').serialize(),
        success: function (message) {
          alert(message);
        }
      });

    });

  });
</script>

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

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