简体   繁体   English

通过使用来自jQuery的两个变量的Ajax的PHP文件请求

[英]Php file request through ajax using two variables from jquery

I have this: A javascript file that does a request to a php file. 我有这个:一个对php文件发出请求的javascript文件。

I have two variables called Lat and Lng in my javascript. 我的JavaScript中有两个名为Lat和Lng的变量。 When I do the request to the php file with ajax I would like those two variables to be translated in to php values that the php file will use. 当我使用ajax对php文件进行请求时,我希望将这两个变量转换为php文件将使用的php值。

I hope this explains it clear enough. 我希望这可以解释得足够清楚。 How can I do this? 我怎样才能做到这一点?

Code: Javascript 程式码:Javascript

var lng = center.lng();
var lat = center.lat();
$.ajax({
    url: "ajax.php"
}).done(function(data){};

Code: Php 代码:PHP

$lat = '';
$lng = '';

What I want is those two variable values from the Javascript in the php with each request. 我想要的是每个请求中来自php中Javascript的两个变量值。

If it helps to know what I'm doing exactly: I'm getting the longtitude and latitude from the google maps center. 如果它有助于知道我在做什么,那么:我正在从Google地图中心获取经度和纬度。 These values I want to use in the file_get_contents url in my php. 我想在PHP的file_get_contents网址中使用这些值。 Every time the request happens the url gets dynamic because the values will be send with the request. 每次请求发生时,URL都会动态变化,因为这些值将随请求一起发送。

Script to request php file through POST data: 通过POST数据请求php文件的脚本:

<script type='text/javascript'>
var longitude = center.lng();
var latitude = center.lat();
$.ajax({
    type: 'POST',
    url: "ajax.php",
    data:{longitude:longitude, latitude:latitude},
    success: function(){
        alert('Success');
    }
}).done(function(data){console.log(data);};
</script>

And in PHP file: you can get values as: 在PHP文件中:您可以通过以下方式获取值:

$longitude = $_POST['longitude'];
$latitude = $_POST['latitude'];

Hope this helps!!! 希望这可以帮助!!!

you need to send the variables through your ajax request first of all. 您首先需要通过ajax请求发送变量。 I use something like this 我用这样的东西

{lng:lng,lat:lat},

and then you make a request in php something like this 然后在php中发出这样的请求

if ($_REQUEST['lng']) {
    $lng = $_POST['lng'];
    $lat = $_POST['lat']
} 

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

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