如何在同一页面上将ajax val传递给php变量?

时间:2016-08-05 01:48:12

标签: javascript php jquery ajax yii2

$('#test-test_id').change(function() {
        var myValue = $(this).val();
    });

// $getMyValue = $(this).val();

例如,通过使用上面的代码,我想将$(this).val传递给同一页面上的php变量。这怎么可能?

2 个答案:

答案 0 :(得分:2)

windown.location可以使用参数重新加载页面。您可以尝试将val发送到php变量,如下所示......

<input type="text" id="test-test_id">
<?php
   if(isset($_GET["val"])){
     $sent = $_GET["val"];
     echo "<h2>".$sent."</h2>";
   }
?>
<script type="text/javascript">
$('#test-test_id').change(function() {
        var myValue = $(this).val();                            
        window.location = '?val=' + myValue; //redirect page with para ,here do redirect current page so not added file name .                      
    });   

更新无刷新代码

$('#test-test_id').change(function() {

        var myValue = $(this).val();
        $.get("",{val:myValue},function(data){
            $("body").html(data);
        });               
     //you can try with many option eg. "$.post","$.get","$.ajax"
     //But this function are not reload page so need to replace update data to current html
    });   
</script>

答案 1 :(得分:0)

您想要做的事情有点复杂,首先您必须在将变量从客户端传递到服务器时发出AJAX请求,如下所示:

$.post('/', { variable: "your_value_here" }, function() {
   alert('Variable passed');
}); 

这个简单的代码,在Javascript中发送POST请求到您传递的URL作为第一个参数,在这种情况下,我们传递给$ .post相同的页面。现在,在PHP中,您必须处理POST请求:

session_start(); // We start a session where we'll set the value of variable.
if(isset($_POST['variable'])) {
   $_SESSION['your_var'] = $_POST['variable'];
} else {
   /* Your page code */ 
}

您也可以在数据库中注册变量,但如果它是临时变量,您只需在会话中注册即可。在使用session_start()全局变量之前,请务必在每个页面中使用$_SESSION

有用的文档: jQuery.post()PHP Sessions