【发布时间】:2017-08-24 10:33:18
【问题描述】:
我对 Javascript、PHP 和 AJAX 有点陌生。我搜索了很长时间来寻找这个问题的答案,但找不到答案。首先是我的代码:
我的 index.html 文件:
<input type="text" id="value" onkeyup="loadDoc(this.value)">
<p id="demo"></p>
<p id="demo2"></p>
我的 test.js 文件:
function loadDoc(kruispunt) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = kruispunt;
}
};
xhttp.open("POST","link.php?q=" + kruispunt, true);
xhttp.send("kruispunt");
}
function myFunction(){
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onload = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo2").innerHTML = this.responseText;
xhttp.open("GET","link.php", true);
xhttp.send();
}
}
}
我的link.php 文件:
<?php
$kruispunt5= file_get_contents('http://fiwarelab.ckan.nl/api/action/datastore_search? resource_id=0077d99e-127c-4c28-acde-c0f337e13065');
$kruispunt5 = json_decode($kruispunt5, true);
$lat5 = json_encode($kruispunt5['result']['records'][4]['latitude']);
$long5 = json_encode($kruispunt5['result']['records'][4]['longitude']);
$kruispunt11 = file_get_contents('http://fiwarelab.ckan.nl/api/action/datastore_search? resource_id=6b39a68b-54d1-4254-a2ce-af59a8856f3f');
$kruispunt11 = json_decode($kruispunt11, true);
$lat11 = json_encode($kruispunt11['result']['records'][4]['latitude']);
$long11 = json_encode($kruispunt11['result']['records'][4]['longitude']);
$q = $_REQUEST['kruispunt'];
$x = 0;
$y = 0;
if ($q !== "") {
if ($q === "5"){
$x = $lat5;
$y = $long5;
} else if ($q === "11"){
$x = $lat11;
$y = $long11;
}
}
echo json_encode($x);
echo json_encode ($y);
?>
我想要实现的是我的输入值存储在“演示”中,同时将该参数 (kruispunt) 提供给我的 .php 文件。然后我希望我的 .php 文件弄清楚 $x 和 $y 是什么并将其发送回 myFunction() 并将 php 文件中的 $x 和 $y 变量放入我的“demo2”中。
例如,如果我将 5 作为输入值,“demo”确实返回 5,但之后“demo2”中没有显示任何内容,所以我认为我的 POST 或 .php 文件有问题。不知何故,我的浏览器没有出现错误,但也没有任何显示。
我真的希望我能明确我想要实现的目标,并提前感谢您解决或帮助解决我的问题!
【问题讨论】:
-
收到完整值后是否应该不运行loadDoc? 5 还是 11?
-
您是否要返回两个 json?如果是这样,为什么?您可以合并两个数组并返回一个,然后您可以使用 javascript 解析它。同样在您的 php 中,在回显 json 字符串之前添加标头
-
@mplungjan 我以为我正在这样做,所以是的,这就是我想要的
-
@LeaTano 哦,是的,我会将它们合并为我的错误.. 我如何用 javascript 解析它?你的意思是什么标题?
-
在回显之前包含以下代码。 header('Content-Type: application/json');
标签: javascript php json ajax google-chrome