我嘗試從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