在PHP变量中获取Javascript变量值

时间:2017-03-02 12:20:44

标签: javascript php jquery html



    var val;
    $('select').on('change', function() {
        alert( this.value );
        val = this.value;
    })
    
    <?php
echo $variable = "<script>document.write(val)</script>";
?>
&#13;
<select>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">four</option>

</select>
&#13;
&#13;
&#13;

我想获取所选框的值并将其保存在PHP变量中。我想保存并回显val变量。请帮忙

2 个答案:

答案 0 :(得分:1)

将此代码用于使用变量

  <?php
  session_start();
  echo $_SESSION['php_value'];
  ?>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    function getValue(obj){
    var value = obj.value;
    $.ajax({
        type:"POST",
        url: 'edit.php',
        data: "val="+ value,
        dataType: 'text',
        async: false,
        cache: false,
        success: function ( result )  {
            window.location.reload();
        }
    });
}

</script>

<select onchange="getValue(this)">
<option value="1" <?php if($_SESSION['php_value'] == 1) echo 'selected';?>>One</option>
<option value="2" <?php if($_SESSION['php_value'] == 2) echo 'selected';?>>Two</option>
<option value="3" <?php if($_SESSION['php_value'] == 3) echo 'selected';?>>Three</option>
<option value="4" <?php if($_SESSION['php_value'] == 4) echo 'selected';?>>four</option>

</select>

然后创建edit.php文件

<?php
 session_start();
 $_SESSION['php_value'] = $_REQUEST['val'];
?>

答案 1 :(得分:0)

Ajax可以做到这一点。谷歌吧,查看api.jquery.com并查看ajax函数,.ajax(),。post(),. get(),. load()等。

至于你的具体问题,这是你要做的:

//Javascript file

$.post('my_ajax_receiver.php', 'val=' + $(this).val(), function(response) {
  alert(response);
  });

});

//PHP file my_ajax_receiver.php
<?php
   $value = $_POST['val'];
   echo "$value";
?>