PHP中的Javascript变量 [英] Javascript variable in PHP
问题描述
使用HTML5 Geolocation API我最终得到了Javascript中的一些变量,我需要传递给PHP才能继续。我的代码在下面,怎么可能实现?我尝试过类似 $ variable =< script> document.write(variable);< / script> ;;
Using the HTML5 Geolocation API I've ended up with some variables in Javascript that I need to pass to PHP in order to continue. My code is below, how could it be achieved? I've tried things along the lines of $variable = <script>document.write(variable);</script>;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=620" />
<title>test</title>
</head>
<body>
<script type="text/javascript">
//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
else {
document.write("Geolocation is required for this page.");
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
}
function errorFunction(position) {
document.write("Error");
}
</script>
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$lat = //TAKE FROM JAVASCRIPT
$lng = //TAKE FROM JAVASCRIPT
$url = "http://api.geonames.org/findNearbyPlaceNameJSON?lat='.$lat.'&lng='.$lng.'&username=demo";
$json = file_get_contents($url);
$data = json_decode($json, true);
$geonames = $data['geonames'][0];
$town = $geonames['name'];
echo "Displaying results near ".$town.". <a href=#>Not in ".$town."?</a>";
?>
</body>
</html>
编辑:好的,我做了一些功课,现在我知道我在看AJAX XMLHttpRequest可以浏览两者。但是,它的语法略微抛弃了我(更不用说跨浏览器问题了)。任何人都可以给我一个正确的方向吗?
OK, I've done some homework and now I know I'm looking at an AJAX XMLHttpRequest to slick over the two. However, its syntax has slightly thrown me (not to mention the cross-browser issues). Can anyone give me a nudge in the right direction with this one?
推荐答案
您正在混合服务器端脚本和浏览器 - 边脚本
You are mixing Server-side scripting along with browser-side scripting
浏览器端的$ variable dissapears因此它将始终保持document.write(variable);无论里面的脚本是什么写的。
$variable dissapears on the browser-side and so it will always hold "document.write(variable);" whatever the script inside there is written in.
然而,您可以使用AJAX将数据发送回php&在那里处理它。
You can however use AJAX to send the data back to php & process it there.
这篇关于PHP中的Javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!