数据未传递到 php 文件
Data not passing to php file
通过 AJAX 将用户地理定位发送到 php 文件时遇到问题。
这里是代码:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
$.ajax({
type: 'POST',
data: pos,
url: '/template-userslocation.php'
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
};
尝试过多种写入数据的方法,例如:
data: {pos}
,
data:({pos})
,
data: {lat: position.coords.latitude, lng: position.coords.longitude},
这是我在 template-userslocation.php
:
中遇到的错误
Notice: Undefined index: pos in /home/.../template-userslocation.php on line 7
已解决:
问题是我一直在使用 Wordpress,它有自己的处理方式 javascript:
pos
是变量名,从PHP它不会知道,它只会看到$_POST['lat']
和$_POST['lng']
所以使用:
$.ajax({
type: 'POST',
data: {'pos': pos},
url: '/wp-content/themes/atripby/template-userslocation.php'
});
然后从PHP访问像:
$lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
$lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
通过 AJAX 将用户地理定位发送到 php 文件时遇到问题。
这里是代码:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here');
map.setCenter(pos);
$.ajax({
type: 'POST',
data: pos,
url: '/template-userslocation.php'
});
},
function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
};
尝试过多种写入数据的方法,例如:
data: {pos}
,
data:({pos})
,
data: {lat: position.coords.latitude, lng: position.coords.longitude},
这是我在 template-userslocation.php
:
Notice: Undefined index: pos in /home/.../template-userslocation.php on line 7
已解决:
问题是我一直在使用 Wordpress,它有自己的处理方式 javascript:
pos
是变量名,从PHP它不会知道,它只会看到$_POST['lat']
和$_POST['lng']
所以使用:
$.ajax({
type: 'POST',
data: {'pos': pos},
url: '/wp-content/themes/atripby/template-userslocation.php'
});
然后从PHP访问像:
$lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
$lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;