【发布时间】:2019-12-07 08:26:13
【问题描述】:
$("b_xml").onclick=function(){
new Ajax.Request("books.php", {
method:"GET",
parameters: {category:getCheckedRadio(document.getElementsByName("category"))},
onSuccess: showBooks_JSON,
onFailure: ajaxFailed
})
}
单击按钮时,会创建新的 Ajax 请求并从 books.php 调用数据。 所以我使用 getElementByName 来收集所有命名为“category”的单选按钮 这是我的html代码
<label><input type="radio" name="category" value="children" checked="checked"/> Children</label>
<label><input type="radio" name="category" value="computers" /> Computers</label>
<label><input type="radio" name="category" value="cooking" /> Cooking</label>
<label><input type="radio" name="category" value="finance" /> Finance</label>
和books.php
<?php
$BOOKS_FILE = "books.txt";
function filter_chars($str) {
return preg_replace("/[^A-Za-z0-9_]*/", "", $str);
}
if (!isset($_SERVER["REQUEST_METHOD"]) || $_SERVER["REQUEST_METHOD"] != "GET") {
header("HTTP/1.1 400 Invalid Request");
die("ERROR 400: Invalid request - This service accepts only GET requests.");
}
$category = "";
$delay = 0;
if (isset($_REQUEST["category"])) {
$category = filter_chars($_REQUEST["category"]);
}
if (isset($_REQUEST["delay"])) {
$delay = max(0, min(60, (int) filter_chars($_REQUEST["delay"])));
}
if ($delay > 0) {
sleep($delay);
}
if (!file_exists($BOOKS_FILE)) {
header("HTTP/1.1 500 Server Error");
die("ERROR 500: Server error - Unable to read input file: $BOOKS_FILE");
}
header("Content-type: application/xml");
print "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
print "<books>\n";
$lines = file($BOOKS_FILE);
for ($i = 0; $i < count($lines); $i++) {
list($title, $author, $book_category, $year, $price) = explode("|", trim($lines[$i]));
if ($book_category == $category) {
print "\t<book category=\"$category\">\n";
print "\t\t<title>$title</title>\n";
print "\t\t<author>$author</author>\n";
print "\t\t<year>$year</year>\n";
print "\t\t<price>$price</price>\n";
print "\t</book>\n";
}
}
print "</books>";
?>
我检查了 books.txt 不为空 当我单击按钮时,警报有效,但它返回空框。 什么是问题?
【问题讨论】:
-
成功函数称为
showBooks_JSON- 但您的PHP 清楚地响应XML ...即使没有看到showBooks_JSON函数,很明显您的浏览器控制台中可能存在您未提及的错误 -
但是 showBooks_XML 和 showBooks_JSON 是完全一样的功能。它们同样返回 ajaxresponsetext。我尝试在将 showBooks_JSON 更改为 showBooks_XML 后运行它,但它同样返回空值
-
你没有显示函数 - 它可能做错了什么
-
function showBooks_XML(ajax) { alert(ajax.responseText); } function showBooks_JSON(ajax) { alert(ajax.responseText); }这是我的功能。他们是一样的 -
我想第一步将通过一些基本的故障排除来缩小问题范围,而您似乎没有这样做。查看ajax请求。 PHP 是否返回您所期望的?如果是这样,这是一个 Javascript 问题。如果不是,那就是 PHP 问题。
标签: javascript php ajax xml