如何在同一页面上将ajax val传递给php变量?
问题描述:
$('#test-test_id').change(function() {
var myValue = $(this).val();
});
// $getMyValue = $(this).val();
例如,通过使用上面的代码,我想通过$(this).val
到同一页面上的php变量。这怎么可能?如何在同一页面上将ajax val传递给php变量?
答
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>
答
你想要做的是有点复杂,首先你必须做一个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
全局变量之前,请在每个页面中使用session_start()
。
帮助文档: jQuery.post(), PHP Sessions
使一个XMLHttpRequest或使用表格并提交 – Ghost
同意@Ghost。用参数调用本身会使AJAX在这里无用。 – noob