如何将Javascript变量传递给Ajax,然后将其发布到php。 Javacript代码和PHP代码可以正常工作,但问题是将Javascript变量传递给Ajax以发布到PHP。我的代码在
下<!-- User Location -->
<script>
window.onload = function() {
var startPos;
var geoSuccess = function(position) {
startPos = position;
document.getElementById('startLat').innerHTML = startPos.coords.latitude;
document.getElementById('startLon').innerHTML = startPos.coords.longitude;
$.ajax({
type: 'POST',
url: 'MyDashboard.php',
data: 'latitude='+latitude+'&longitude='+longitude,
success: function(msg) {
if (msg) {
$("#location").html(msg);
} else {
$("#location").html('Not Available');
}
}
});
};
navigator.geolocation.getCurrentPosition(geoSuccess);
};
</script>
答案 0 :(得分:1)
不确定您要问什么 但只是
data:`latitude=${startPos.coords.latitude}&longitude=${startPos.coords.longitude}`
答案 1 :(得分:0)
您应该将数据作为USE my_target_db;
SET @origin_db='my_origin_db';
SET @origin_table = CONCAT(@origin_db,'.','tablename');
SET @query = CONCAT('INSERT INTO target_table SELECT * FROM ', @origin_table);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
之类的对象进行传递
data: {latitude: latitude, longitude:longitude }
并输入<script>
window.onload = function() {
var startPos;
var geoSuccess = function(position) {
startPos = position;
document.getElementById('startLat').innerHTML = startPos.coords.latitude;
document.getElementById('startLon').innerHTML = startPos.coords.longitude;
$.ajax({
type: 'POST',
url: 'MyDashboard.php',
data: {latitude: startPos.coords.latitude, longitude: startPos.coords.longitude },
success: function(msg) {
if (msg) {
$("#location").html(msg);
} else {
$("#location").html('Not Available');
}
}
});
};
navigator.geolocation.getCurrentPosition(geoSuccess);
};
</script>
和$_POST['latitude']
之类的php代码
答案 2 :(得分:0)
问题是latitude
和longitude
变量不存在。.
尝试以下代码:
<!-- User Location -->
<script>
window.onload = function() {
var geoSuccess = function(position) {
document.getElementById('startLat').innerHTML = position.coords.latitude;
document.getElementById('startLon').innerHTML = position.coords.longitude;
$.ajax({
type: 'POST',
url: 'MyDashboard.php',
data: 'latitude=' + position.coords.latitude+ '&longitude=' + position.coords.latitude,
success: function(msg) {
if (msg) {
$("#location").html(msg);
} else {
$("#location").html('Not Available');
}
}
});
};
navigator.geolocation.getCurrentPosition(geoSuccess);
};
</script>
并通过调用这些变量$_POST['latitude']
和$_POST['longitude']
答案 3 :(得分:0)
您正在传递未定义的变量。请尝试这个:
$.ajax({
type: 'POST',
url: 'MyDashboard.php',
data: {
latitude: startPos.coords.latitude,
longitude: startPos.coords.longitude
},
success: function(msg) {
// your logic
});
答案 4 :(得分:-2)
您将错误的数据发送到AJAX POST方法
数据:{'纬度':纬度,'经度':经度}
发送AJAX的位置
数据:'latitude ='+纬度+'&longitude ='+经度,
或者您可以在URL上添加它们
url:'MyDashboard.php?latitude ='+纬度+'&longitude ='+经度
这也将起作用,但是$ _GET需要在php中使用$ _POST