如何在Mac上使用Ajax将Javascript变量发送到PHP?

问题描述 投票:0回答:1

我有一个基本代码,我正在其中尝试使用ajax将输入框的值发送到PHP。

我正在将数据从try.php发送到books2.php。

我的try.php代码

<!DOCTYPE html>
<html>
<body>
  <form method="post">
  <input type="number" min="0" id="Q1" name="Q1" method="post"><br>
  <input type="number" min="0" id="Q2" name="Q2" method="post"><br>
  <input type="number" min="0" id="Q3" name="Q3" method="post">
  <input type="submit" id="submit2">
  </form>
<h2 id="content"></h2>
<script type="text/javascript" src="jquery-3.4.1.js"></script>
<script>
  $("#submit2").click(function(){
    var q1 = $("#Q1").val()
    var q2 = $("#Q2").val()
    var q3 = $("#Q3").val()
    $.ajax({
      url:"books2.php",
      data:{"Quantity1":q1},
      success:function(data){
        $('#content').html(data)
      }

    })
  })
</script>
</body>
</html>

我的books2.php代码

<?php
if(isset($_POST['Quantity1'])){
  echo $_POST['Quantity1'];
}else {
  echo "failed";
}
?>

谢谢你。

javascript php ajax
1个回答
0
投票

您的代码中有很多错误。

我想从;开始,您想念他们。

那为什么要在输入上输入method="post"

您不需要FORM,因为它会重定向您。

您的JQUERY源脚本不起作用。

[在POST中使用AJAX时,必须在POST脚本中使用AJAX

所以这是代码:

HTML代码:

<!DOCTYPE html>
<html>
<body>
    <input type="number" min="0" id="Q1" name="Q1"><br>
    <input type="number" min="0" id="Q2" name="Q2"><br>
    <input type="number" min="0" id="Q3" name="Q3">
    <input type="submit" id="submit2">
<h2 id="content"></h2>
</body>
</html>

jQuery代码:

$("#submit2").click(function(){
        var q1 = $("#Q1").val();
        var q2 = $("#Q2").val();
        var q3 = $("#Q3").val();
        $.ajax({
            url:"books2.php",
            method: "POST",
            data:{"Quantity1":q1},
            success:function(data){
                $('#content').html(data);
            }

        });
    });

和AJAX代码:

if(isset($_POST['Quantity1'])){
    echo $_POST['Quantity1'];
}else {
    echo "failed";
}
© www.soinside.com 2019 - 2024. All rights reserved.