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

时间:2013-09-29 17:53:11

标签: javascript php

我搜索了一个多小时,尝试了很多例子,但没有人做我需要的。从JavaScript我可以使用<b id="citynm"></b>在PHP或HTML中显示必要的变量,但我需要生成citynm $citynm。我第一次尝试使用AJAX,但只能点击按钮或页面刷新。

我需要运行JavaScript来获取citynm,然后将其转换为$citynm以便在任何页面上使用PHP,而无需再次运行JS。 JS只在进入网站后运行一次。但$citynm将在不同需求的几个页面上运行(例如echo "You live in ".$citynm)。

2 个答案:

答案 0 :(得分:0)

最好的方法是将citynm所需的值存储到会话变量中,如下所示:

$_SESSION['citynm'] = $citynm

您必须在页面加载或ajax上执行此操作。然后,您可以在自全球以来的任何页面中使用$ _SESSION ['citynm']。

答案 1 :(得分:0)

USECASE 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'];

?>

USECASE 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);