我创建了一个非常基本的页面,它使用 AJAX 从我的 contact
MySQL 表中检索所有联系人:
index.php
html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>mycontacts.</title>
<script type="text/javascript" src="JavaScripts/PrintContacts.js"></script>
</head>
<body>
<div class="main-wrapper">
<div id="main-content">
<script type="text/javascript">
printContacts();
</script>
<div id="contacts">
</div>
</div>
</div>
</body>
</html>
PrintContacts.js
var xmlHttp;
function printContacts() {
xmlHttp = new XMLHttpRequest();
var url = "PHP/getAllContacts.php";
// Workaround for page caching
url = url + "&sid=" + Math.round(Math.random() * 1000000000);
// Commenting the line above removes my issue but I do need this for caching!!!
// Manage XmlHttpObject state change
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("POST", url, true);
xmlHttp.send(null);
}
function stateChanged() {
// Check if the XmlHttp request is complete
if (xmlHttp.readyState == 4) {
// Set the XmlHttp response in the div contacts
document.getElementById("contacts").innerHTML = xmlHttp.responseText;
}
}
getAllContacts.php
<?php
$dbconnection = mysql_connect("localhost", "root", "");
mysql_select_db("mycontacts", $dbconnection);
$command = "SELECT * FROM contact";
$result = mysql_query($command);
echo "<table border='1'>";
// Table headers
echo "<tr><th>Name</th></tr>";
// Print all contacts
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['DisplayName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($dbconnection);
?>
打开 getAllContacts.php 会直接返回包含数据的相应表,但是,打开 index.php 会导致错误:
Object not found!
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.
If you think this is a server error, please contact the webmaster.Error 404
localhost
12/08/2010 2:47:27 PM
Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
我发现添加 &SID= 是问题的根源。这发生在 PrintContacts.js 文件中。删除它会正确加载页面。但我确实需要它来解决缓存问题。你知道如何解决这个问题吗?
感谢大家的帮助。
解决方案
将 SID 添加到 url 时(用于缓存目的),应附加“?sid=”而不是“&sid=”。更改此设置可以解决问题;毕竟这是一个错字!
function printContacts() {
xmlHttp = new XMLHttpRequest();
var url = "PHP/getAllContacts.php";
// Workaround for page caching
url = url + "&sid=" + Math.round(Math.random() * 1000000000);
...
最佳答案
使用 AJAX 时,应该根据浏览器的当前位置链接 url,而不是 javascript 文件的位置。
将 printContacts() 中的 url 更改为“PHP/getAllContacts.php”。
编辑:好的...我想通了!在 PrintContacts.js 中,您需要更改此行
url = url + "&sid=" + Math.round(Math.random() * 1000000000);
对此...
url = url + "?sid=" + Math.round(Math.random() * 1000000000);
请注意其中的问号。使用 & 使其查找名为 getAllContacts.php&192837 的文件,而不是名为 getAllContacts.php 的文件。
关于php - 在 AJAX 中调用 PHP 脚本时出现错误消息 : Object not found!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4388611/