如何使用Javascript AJAX将值传递给第二页

时间:2016-09-02 06:59:48

标签: javascript php html ajax

我的页面上有一个html选择

<pre>
$query = mysql_query("select * from results");
echo "<select id='date' onchange='showdata()' class='form-control'>";
while ($arr = mysql_fetch_array($query)) {
echo "<option value=".$arr['month'].">".$arr['month']." / ".$arr['year']. "</option>" ;   
}
echo "</select>";
</pre>

选项来自数据库。在此之后我有ajax脚本

<script>

function showdata() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML = this.responseText;
    }
  };

  xhttp.open("GET", "result.php", true);
  xhttp.send();
}

</script>

我希望它将html选择中的选定值发送到页面result.php

2 个答案:

答案 0 :(得分:0)

试试这个:

$someVariable = $_GET["someVariable"];
$query = mysql_query("select * from results");
        echo "";
        while ($arr = mysql_fetch_array($query)) {
        echo "".$arr['month']." / ".$arr['year']. "" ;

        }
        echo "";

和JS:

<script>

function showdata() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML = this.responseText;
    }
  };

  xhttp.open("GET", "result.php?someVariable=test", true);
  xhttp.send();
}

</script>

如果您需要POST示例,请访问Send POST data using XMLHttpRequest

答案 1 :(得分:0)

使用jquery ajax执行相同操作的另一种方法...

<select id="item" onchange="send_item(this.value)">
 <?php $someVariable = $_GET["someVariable"];
       $query = mysql_query("select * from results");
       echo "";
     while ($arr = mysql_fetch_array($query)) {?>
<option value="<?php echo your value?>"><?php echo your value?></option>
   <?php }?>
</select>



  <script>
  function send_item(str){
    $.ajax({
        url: '',
        type: "post",
        data: {
           'str':str,
        },
        success: function(data) {

        },
    });
 }
    </script>