我有一个应用程序,它将纬度,经度值发送到我的postgresql数据库。我想使用jquery,ajax在我的OpenLayers地图上相应地绘制更新的点。但这里是我被困在的地方:当我点击按钮时,带有数据库连接的php文件并保存数组中表的最后一个条目正在发生。
但是当我尝试在标记中使用输出时,没有任何事情发生。
如何在我的函数中使用php的输出值?
以下是我尝试使用的代码。
php文件:
<?php
$conn = pg_connect("host=xxx port=xxx dbname=xx user=postgres password=xxx");
$result = pg_exec($conn,"Query goes here");
$numrows = pg_numrows($result);
for($ri = 0; $ri < $numrows; $ri++)
{
$row = pg_fetch_array($result, $ri);
$data = array(); // create a variable to hold the information
$lat_latest[] = $row["latitude"];
$long_latest[] = $row["longitude"]; // add the row in to the results (data) array
}
pg_close($conn);
$js_lat = json_encode($lat_latest);
echo "var javascript_lat1 = ". $js_lat . ";\n";
$js_long = json_encode($long_latest);
echo "var javascript_long1 = ". $js_long . ";\n";
?>
我的网页代码是:
function init(){
//openlayers map code is here.
$("button").click(function(){
$.get("dataconn.php",function(data,status){
alert("Data:"+data+"Status:" +status);
var extra_point = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(parseFloat(javascript_long1[0]),parseFloat(javascript_lat1[0])),
{some:'data'},
{externalGraphic: 'images1/marker-gold.png', graphicHeight: 16, graphicWidth: 16});
vectorLayer1.addFeatures([extra_point]);
});
});
}
</script>
</head>
<body onload='init();'>
<div id="map" style = 'width: 1075px; height: 485px'>
<button> Update </button>
</div>
点击更新按钮后我收到的提醒
Data:
var javascript_lat1 = ["output of the query"];
var javascript_long1 = ["output of the query"];
Status : success
我试图访问查询输出值的方式是否正确?请帮忙。 对不起,如果这是一个愚蠢的问题。我是jquery的新手。
答案 0 :(得分:1)
当你的php脚本发送一个字符串,如:
'var javascript_lat1 = ["output of the query"];'
回到你的代码,这并不意味着你的代码中有一个名为javascript_lat1的变量。
您的php脚本正在将字符串发送回您的javascript代码,您必须从中提取要在代码中使用的信息。由你的javascript代码来了解字符串的格式。但是,既然你编写了php脚本,你可以以任何你想要的格式发回字符串。然后你的javascript代码可以用正则表达式,split()等来剖析字符串,以提取你想在代码中使用的字符串部分。您的PHP代码可以使用的一种非常简单的格式是:
"output of query 1, output of query 2"
然后你可以在逗号上分割()以分隔两个数据,例如:
var pieces = data.split(', ');
然后你可以在你的javascript代码中使用piece [0]和pieces [1]。
另一种选择是使用$ .getJSON()函数向您的php脚本发送请求。如果你这样做,你的PHP脚本应该发回一个json格式的字符串,例如:
"{lat1: 'blah blah blah', long1: 'foo bar foo bar'}"
然后$ .getJSON()函数会自动将字符串转换为javascript对象并将js对象传递给回调函数。在回调函数中,您可以使用以下方法访问数据:
some_func(data.lat1, data.long1);