$('#test-test_id').change(function() {
var myValue = $(this).val();
});
// $getMyValue = $(this).val();
例如,通過使用上面的代碼,我想通過$(this).val
到同一頁面上的php變量。這怎麼可能?如何在同一頁面上將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