我尝试从JavaScript(当在表单中选择某个选项时)将一个变量传递给调用SQL查询的PHP文件。将PHP变量传递给Javascript函数可以提供一个AJAX请求吗?
应将SQL查询(字符串)切换到Javascript函数并执行该函数。一切都在一个点击。这是否有可能?
我试过用AJAX请求,但是当我使用这个对我的最后一步:
var javascriptstring;
$.getJSON('getstring.php', function(data) {
javascriptstring = data.value;
});
I get the exception: Uncaught TypeError: Cannot set property 'innerHTML' of null
而且它打印出 “不确定”
.HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
function showString(time) {
if (time=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getstring.php?q="+time,true);
xmlhttp.send();
var javascriptstring;
$.getJSON('getstring.php', function(data) {
javascriptstring = data.value;
});
document.write(javascriptstring);
}
</script>
</head>
<body>
<form>
<select name="somestring" onchange="showString(this.value)">
<option value="">No string selected</option>
<option value="1">String 1</option>
</select>
</form>
<br>
<div id="txtHint"><b>String will be listed here...</b></div>
</body>
</html>
PHP
<?php
$q = intval($_GET['q']);
$con = pg_connect("host=localhost port=5432 dbname=Twitter user=postgres password=****");
if (!$con) {
die('Could not connect: ' . pg_errormessage($con));
}
$sql="SELECT * FROM tswholeworld WHERE createdat > (NOW() - INTERVAL '".$q."hour');";
$result = pg_query($con,$sql);
$string = "";
while($row = pg_fetch_assoc($result)){
$lat = $row['latitude'];
$lon = $row['longitude'];
$string .= "new google.maps.LatLng({$lat}, {$lon}), ";
}
echo '{"value": "'.$string.'"}';
pg_close($con);
?>
好吧,看起来不错,但不知何故,它仍然无法正常工作。我想这是因为我的PHP没有得到它的变量:xmlhttp.open(“GET”,“getstring.php?q =”+ time,true);了吗? – Andrej
我可以看到你的jquery脚本没有关闭。 '' – joyBlanks
@Andrej您使用Native Ajax做了同样的事情,然后您再次用jQuery Ajax做这件事。因此,如果您有权访问Jquery,为什么不使用jQuery,所以我已经删除了原生的ajax代码 – joyBlanks