簡體   English   中英

JS變量到PHP變量,無按鈕或刷新

[英]JS variable to PHP variable without buttons or refresh

我已經搜索了一個多小時,並嘗試了許多示例,但沒有一個可以滿足我的需要。 在JavaScript中,我可以使用<b id="citynm"></b>在PHP或HTML中顯示必要的變量,但是我需要使citynm $citynm成為$citynm 我已經嘗試過第一次使用AJAX,但是只能通過單擊按鈕或刷新頁面來使其工作。

我需要運行JavaScript來獲取citynm,然后使其變為$citynm以供PHP在任何頁面上使用,而無需再次運行JS。 進入站點后,JS僅運行一次。 但是$citynm將在不同需求的多個頁面上運行(例如echo "You live in ".$citynm )。

最好的方法是將citynm所需的值存儲到會話變量中,如下所示:

$_SESSION['citynm'] = $citynm

您必須在頁面加載時或通過ajax執行此操作。 然后,您可以在$ _SESSION ['citynm']自全局以來的任何頁面中使用。

用例1:通過用戶輸入

在您的html文件中:

<input type="text" name="citynm" id="citynm" value="Brussels">

在您的javascript文件中(此處使用jquery以提高可讀性):

(function(){

    $('#citynm').on('blur',function(){
    // when the input value has changed, post its value to server.
var citynm = $(this).val();
        $.post('http://domain.com/path/to/your/php/file.php',{citynm: citynm},function(data){

// if the request is successful, the following script will be executed.
alert("server said: "+data);
        });
    });
})(jQuery);

在file.php文件中:

<?php
    session_start();
    if(isset($_POST['citynm']) && strlen($_POST['citynm'])>0){
      $_SESSION['citynm'] = $_POST['citynm'];
    }
echo "citynm is ".  $_SESSION['citynm'];

?>

用例2:無用戶輸入

   var cityname = city.short_name; 
if (status == google.maps.GeocoderStatus.OK) { document.getElementById("citynm").innerHTML = cityname; }

    (function(){

                $.post('http://domain.com/path/to/your/php/file.php',{citynm: cityname},function(data){

        // if the request is successful, the following script will be executed.
        alert("server said: "+data);
                });
        })(jQuery);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM