简体   繁体   English

JS变量到PHP变量,无按钮或刷新

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

I've searched for over an hour and tried many examples but none do what I need. 我已经搜索了一个多小时,并尝试了许多示例,但没有一个可以满足我的需要。 From JavaScript I can display the necessary variable in PHP or HTML with <b id="citynm"></b> but I need to make citynm $citynm . 在JavaScript中,我可以使用<b id="citynm"></b>在PHP或HTML中显示必要的变量,但是我需要使citynm $citynm成为$citynm I've tried looking in AJAX for the first time but could only get it to work with a button click or page refresh. 我已经尝试过第一次使用AJAX,但是只能通过单击按钮或刷新页面来使其工作。

I need to run the JavaScript to get citynm and then make it into $citynm for PHP use on any page without running the JS again. 我需要运行JavaScript来获取citynm,然后使其变为$citynm以供PHP在任何页面上使用,而无需再次运行JS。 The JS is only run once upon entering the site. 进入站点后,JS仅运行一次。 But the $citynm will be run on several pages in different needs (such as echo "You live in ".$citynm ). 但是$citynm将在不同需求的多个页面上运行(例如echo "You live in ".$citynm )。

The best way is to store the value you want for citynm into a session variable as below: 最好的方法是将citynm所需的值存储到会话变量中,如下所示:

$_SESSION['citynm'] = $citynm

You have to do this either at page load, or by ajax. 您必须在页面加载时或通过ajax执行此操作。 Then, you can use $_SESSION['citynm'] in any pages you want since its global. 然后,您可以在$ _SESSION ['citynm']自全局以来的任何页面中使用。

USECASE 1: via user input 用例1:通过用户输入

in your html document: 在您的html文件中:

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

inside your javascript file (using jquery here for readability): 在您的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);

And inside the file.php file: 在file.php文件中:

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

?>

USECASE 2: no userinput 用例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