2016-08-05 32 views
0
$('#test-test_id').change(function() { 
     var myValue = $(this).val(); 
    }); 

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

例如,通過使用上面的代碼,我想通過$(this).val到同一頁面上的php變量。這怎麼可能?如何在同一頁面上將ajax val傳遞給php變量?

+1

使一個XMLHttpRequest或使用表格並提交 – Ghost

+0

同意@Ghost。用參數調用本身會使AJAX在這裏無用。 – noob

回答

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> 
+0

嗨大衛。是否可以在不刷新頁面的情況下執行此操作?因爲我在(#test-test_id)中的選擇將變回默認值 – CloudSeph

+0

是的,你可以看更新回答@IvanCloud –

+0

哇。那完美的作品。謝謝。但我的選擇仍然回到默認狀態。例如,我的下拉列表包含男性和女性的數據。一旦我選擇女性。下拉列表將返回到男性。我怎樣才能防止呢? – CloudSeph

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全局變量之前,請在每個頁面中使用session_start()

幫助文檔: jQuery.post()PHP Sessions

+0

我想asker想打電話給頁面本身。 – noob

+0

是的。我想在頁面本身 – CloudSeph

+0

這是什麼意思?如果您想在整個頁面中創建整個腳本,請確保您能夠完成此操作。我在編輯我的答案,告訴你如何做到這一點。 – Syncro

相關問題