繁体   English   中英

如何在 php 的帮助下回显 ajax 数据?

[英]how to echo the ajax data with the help of php?

我试图打印用户输入的数据,并通过 ajax 传输,并尝试在 php 代码的帮助下打印或回显它,但我做不到。 enter code here这是我的代码:

<html>

  <head>
    <title>
      test ajax
    </title>
    <script src="jquery.js"></script>
  </head>

  <body>
    <h2>test button</h2><br>
    <form>
      <input type="text" id="a"><br>
      <input type="button" id="b" value="display">
    </form>
    <script>
      $(document).ready(function() {
        $('#b').click(function() {
          let a = $('#a').val();
          alert(a);
          $.ajax({
            type: "POST",
            url: "same_file.php",
            data: {
              c: a
            },
            success: function() {}

          });

        });
      });

    </script>
  </body>

</html>
<?php
    extract($_POST);
    if(isset($_POST["c"])) {
    echo $_POST["c"];
    }
 ?>

我认为,php 代码有问题。 请给我任何解决方案。

像这样试试

这是你的 Html

<html>
  <head>
    <title>
      test ajax
    </title>
  <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  </head>
  <body>
    <h2>test button</h2><br>
    <form>
      <input type = "text" id = "a" > <br>
      <input type = "button" id = "b"  value = "display" >
    </form>
  </body>
</html>

<script>
    $(document).ready(function(){
        $('#b').click(function() {
            let a = $('#a').val();
            //alert(a);
            $.ajax({
                type: "POST",
                url: "same_file.php",
                data: {c: a},
                success: function(response) {
                    alert(response);
                }

            });    

        });
    });
</script>

这是你的same_file.php

<?php
//extract($_POST); code works even without this

if(isset($_POST["c"])) {
  echo $_POST['c'];
}
?>

不确定您的 jquery 库调用是否正常,所以我改为调用 web 上的那个。 您的成功:function() 也没有做任何事情,这就是您没有收到任何东西的原因。

还要始终使用一些缩进来格式化您的代码,以便其他人更容易阅读和理解。

您可能希望在渲染主体之前回显。 但实际上,除非您需要处理用户发送的数据,否则您根本不需要 PHP。

事实上,您可能也不需要 jQuery , fetch() 工作得很好。

 $(document).ready(function() { $('#b').click(function() { let a = $('#a').val(); alert(a); $.ajax({ type: "POST", url: "same_file.php", data: { c: a }, success: function() {} }); }); });
 <?php if (isset($_POST["c"])) { // print/echo user data send from form. echo $_POST["c"]; // stop the script from rendering the html below. exit(); }?> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <h2>test button</h2><br> <form> <input type="text" id="a"><br> <input type="button" id="b" value="display"> </form> <!-- add script element with js code here --> </body> </html>

暂无
暂无

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

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