[英]Cannot pass JS variable to PHP using AJAX
I am trying to get current location of user. 我正在尝试获取用户的当前位置。
I have JS script to get current Latitude and Longitude with AJAX to send js variables to index.php. 我有JS脚本可以使用AJAX获取当前的纬度和经度,以将js变量发送到index.php。
$(document).ready(function() {
if ("geolocation" in navigator){
navigator.geolocation.getCurrentPosition(function(position){
var userLat = position.coords.latitude;
var userLong = position.coords.longitude;
console.log(userLong);
console.log(userLat);
$.ajax({
type: 'POST',
url: 'index.php',
data: {
userLat : userLat,
userLong : userLong
},
success: function(data)
{
console.log(data);
}
});
});
}else{
console.log("Browser doesn't support geolocation!");
}});
Then I am trying to do this in my index.php: 然后我试图在我的index.php中做到这一点:
echo $_POST['userLat'];
echo $_POST['userLong'];
Nothing shows up. 什么都没有出现。 Thanks in advance. 提前致谢。
It might help to define and return a dataType
for the ajax. 为ajax定义并返回dataType
可能会有所帮助。
add this to your list of ajax
options 将此添加到您的ajax
选项列表
dataType: 'json',
Then in index.php encode and echo a json string. 然后在index.php中编码并回显json字符串。 Remove the lines 删除线
echo $_POST['userLat'];
echo $_POST['userLong'];
replace them with 替换为
echo json_encode($_POST);
The console.log(data);
console.log(data);
in the success function should show an object with two items: 'userlat' and 'userLong' and associated values for each. 在成功函数中,应该显示一个包含两个项目的对象:“ userlat”和“ userLong”,以及每个项目的关联值。 Or it should if $_POST
had those two items. 或者,如果$_POST
有这两项。
If you want the browser screen to update you will have to take data
and use it to modify the DOM. 如果要更新浏览器屏幕,则必须获取data
并使用它来修改DOM。
Nothing shows up. 什么都没有出现。
And that's correct you will never get any thing by browsing index.php because there is no POST at this time , AJAX is internal and the only way to show a result from index.php is in the page that you send from it an ajax call. 这是正确的 ,你将永远不会通过浏览的index.php因为此时没有POST得到任何东西,AJAX是内部和显示结果从index.php文件是在页面,你从它的一个AJAX调用发送的唯一途径。
At this : 在这 :
success: function(data)
{
console.log(data);
}
you could control where to show your data that comes from index.php by , for example alert(data)
or document.getElementById("someelement").innerHTML=data;
您可以通过来控制显示index.php数据的位置,例如alert(data)
或document.getElementById("someelement").innerHTML=data;
and so on. 等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.