简体   繁体   English

将变量从 javascript 传递到 PHP

[英]Pass variable from javascript to PHP

I'm using Google Maps to make a map that can load markers with lat/lng data stored in a database.我正在使用谷歌地图制作一张地图,该地图可以加载带有存储在数据库中的纬度/经度数据的标记。 I want there to be three different 'layers' that the user can load by clicking buttons.我希望用户可以通过单击按钮加载三个不同的“层”。 When the button is clicked, a php function is executed on the server creating an xml file from the information on the database.单击该按钮时,会在服务器上执行一个 php 函数,根据数据库信息创建一个 xml 文件。 An AJAX function is then called to pull this xml data that is then used to create the map markers.然后调用 AJAX 函数来提取此 xml 数据,然后用于创建地图标记。 Rather than have separate PHP functions for each 'layer' (which would be the same thing except for the line with the SQL query), is there a way to pass a variable from the javascript in the AJAX to the PHP?有没有办法将变量从 AJAX 中的 javascript 传递到 PHP,而不是为每个“层”设置单独的 PHP 函数(除了 SQL 查询的那一行之外,这将是相同的事情)?

If your using AJAX requests it's pretty easy to pass variables to a php file.如果您使用 AJAX 请求,将变量传递给 php 文件非常容易。 Here is a quick example.这是一个快速示例。

 $('#your-button').on("click", function(){
       var somevar1 = "your variable1";
       var somevar2 = "your variable2";
    $.ajax({
        type:"POST",
        url: "your-phpfile.php",
        data: "variable1=" + somevar1 + "\u0026variable2="+ somevar2,
        success: function(){
        //do stuff after the AJAX calls successfully completes
    }

    });
});

Then in your php file you simple access the varables using然后在您的 php 文件中,您可以使用

 $ajax_var1 = $_POST['variable1'];
 $ajax_var2 = $_POST['variable2'];

Please try this:请试试这个:

We can pass a value from javascript to PHP.我们可以将一个值从 javascript 传递给 PHP。

we can use as,我们可以用作,

$getValue = "<script>document.write(your script variable);</script>";

If you do an ajax get request with the following url如果您使用以下网址执行 ajax get 请求

somePhpFile.php?varName=10

Within your somePhpFile.php, you can do在你的 somePhpFile.php 中,你可以做

$v = $_GET['varName'];

Here is Mike Williams' (v2) tutorial on "The AJAX Philosophy" , where he does exactly what you are asking about.这是 Mike Williams 关于“AJAX 哲学”的 (v2) 教程,他完全按照您的要求执行。

(I should note that the map uses Google Maps API v2, but this concept is not API version specific) (我应该注意到地图使用 Google Maps API v2,但这个概念不是特定于 API 版本的)

Quote From Vijay S :引用 Vijay S 的话:

Please try this:请试试这个:

We can pass a value from javascript to PHP.我们可以将一个值从 javascript 传递给 PHP。

we can use as,我们可以用作,

$getValue = echo "<script>document.write(your script variable);</script>";

Modified a little bit it worked good for me :稍微修改了一下,对我很有用:

$getValue = "<script>document.write(YourVarHere);</script>";
echo $getValue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM