JS变量到PHP变量,没有按钮或刷新


JS variable to PHP variable without buttons or refresh

我已经搜索了一个多小时,尝试了很多例子,但没有一个能满足我的需求。从JavaScript中,我可以使用<b id="citynm"></b>在PHP或HTML中显示必要的变量,但我需要使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);

在文件内部.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);