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

我有一个基本代码,我正在尝试使用 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";

}

?>

先感谢您。


守候你守候我
浏览 95回答 1
1回答

九州编程

您的代码中有很多错误。我想开始;,你想念他们。那为什么你有method="post"at 输入?你不需要FORM,因为它会重定向你。您的JQUERY源脚本不工作。当你POST在你的脚本AJAX中使用时,你必须POST在你的AJAX脚本中使用。所以这是代码:HTML 代码:<!DOCTYPE html><html><body>&nbsp; &nbsp; <input type="number" min="0" id="Q1" name="Q1"><br>&nbsp; &nbsp; <input type="number" min="0" id="Q2" name="Q2"><br>&nbsp; &nbsp; <input type="number" min="0" id="Q3" name="Q3">&nbsp; &nbsp; <input type="submit" id="submit2"><h2 id="content"></h2></body></html>jQuery代码:$("#submit2").click(function(){&nbsp; &nbsp; &nbsp; &nbsp; var q1 = $("#Q1").val();&nbsp; &nbsp; &nbsp; &nbsp; var q2 = $("#Q2").val();&nbsp; &nbsp; &nbsp; &nbsp; var q3 = $("#Q3").val();&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url:"books2.php",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; method: "POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data:{"Quantity1":q1},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success:function(data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#content').html(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });和 AJAX 代码:if(isset($_POST['Quantity1'])){&nbsp; &nbsp; echo $_POST['Quantity1'];}else {&nbsp; &nbsp; echo "failed";}
打开App,查看更多内容
随时随地看视频慕课网APP