【发布时间】:2018-02-24 18:02:54
【问题描述】:
我对我的作业要求感到困惑:我们需要将 JS、HTML 和 PHP 代码放在同一个文件 xxx.php 中。
HTML 中有一个表单,一旦我提交表单,我需要使用表单输入向 myPHP.php 发送请求 (XMLHTTPRequest)(使用 POST 传输表单数据 PHP)。 PHP 文件将检索表单输入,将其重新格式化为 API 的语法并将其发送到 Google API 以获取 JSON 对象。
我是PHP和JS的初学者,我不知道如何将它们组合在同一个文件中并根据要求做功课。比如,如何将 PHP 中获取的 JSON 对象发送到 Javascript。
这是我的代码框架(myPHP.php):
<html>
<head>
<script type="text/javascript">
// show the result
function show() {
var xmlhttpreq = new XMLHttpRequest();
var keyword = document.getElementById("keyword").value;
var post_data = "keyword=" + keyword;
xmlhttpreq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
createTable(jsonObj);
}
};
xmlhttpreq.open("POST", "myPHP.php", true);
xmlhttpreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttpreq.send(post_data);
}
function createTable(object) {
var out = "xxx";
document.getElementById("display").innerHTML = out;
}
</script>
</head>
<body>
<div id="display"></div>
<form action="myPHP.php" name="myForm" method="POST">
<b>Keyword </b><input type="text" id="keyword" name="keyword">
<br>
<button type="submit" onclick="show()" name="search">Search</button>
</form>
<?php
if (isset($_POST["search"])) {
// extract the form data
$keyword = $_POST["keyword"];
// geocode the address
$location = urlencode($location);
// google map geocode api url
$url = "xxxxxxxx";
$res_json = file_get_contents($url);
echo $res_json;
}
?>
</body>
</html>
【问题讨论】:
-
您是否意识到
<?php之前的所有内容也会在对POST 请求的响应中输出?是否要求所有代码都必须在一个文件中?这很容易完成,您只需要了解 PHP 的工作原理 - 因此,pastebin.com/MFGSNrrp 之类的内容更接近您想要的 -
这不可能。你确定你正确地解释了你的作业指导吗?该页面当前包含内联 PHP 的杂乱组合,看起来它应该对 HTML 做出贡献,并且如果表单回发回自身(如
-
现在我已经尝试了 Jaromanda 的解决方案。但是,我无法在 JS 中获取数据。显示响应状态为0,不知道哪里出错了。我只想在“display”div中显示获取到的数据,但是什么都没有。
标签: javascript php html json xmlhttprequest