将变量从javascript传递到PHP [英] Pass variable from javascript to PHP

查看:93
本文介绍了将变量从javascript传递到PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Maps制作可以加载数据库中存储的经纬度数据的标记的地图。我希望用户可以通过单击按钮来加载三个不同的图层。单击该按钮时,将在服务器上执行php函数,从而根据数据库中的信息创建xml文件。然后调用AJAX函数提取此xml数据,然后将其用于创建地图标记。
不是每个层都有单独的PHP函数(除了SQL查询所在的行,这是相同的东西),有没有办法将AJAX中的javascript变量传递给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. An AJAX function is then called to pull this xml data that is then used to create the map markers. 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请求,则很容易将变量传递给php文件。这是一个简单的例子。

If your using AJAX requests it's pretty easy to pass variables to a php file. 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
    }

    });
});

然后在您的php文件中,使用

Then in your php file you simple access the varables using

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

这篇关于将变量从javascript传递到PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆