gpt4 book ai didi

javascript - 可以在 AJAX 请求中将 PHP 变量传递给 Javascript 函数吗?

转载 作者:行者123 更新时间:2023-12-01 05:38:29 24 4
gpt4 key购买 nike

我尝试将变量从 Javascript(在表单中选择某些选项时)传递到调用 SQL 查询的 PHP 文件。

应将 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);
?>

最佳答案

我想这么多的 AJAX 应该足够了。实际上 document.write 将整个 DOM 替换为当前的 DOM。我已经删除了它并修改了你的功能。另外,我已经删除了 native Ajax 代码,因为您已经有了 jQuery,所以没有必要添加那么大的代码。这个小函数将获取 JSON 数据并打印服务器发送的值

<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;
}
$.getJSON('getstring.php?q='+time, function(data) {
document.getElementById("txtHint").innerHTML = data.value;
});
}
</script>

编辑:请关闭外部脚本标签

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
//your script
</script>

关于javascript - 可以在 AJAX 请求中将 PHP 变量传递给 Javascript 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32437210/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com