我的电脑上有一个本地 apache 2.2 服务器。我在我的系统上使用 PHP 5 和 MySQL 5.0。我在我的 MySQL 数据库中创建了一个名为 html5 的表,该表有一列和一行包含任意字符串。
我创建了一个名为 sample.php 的 PHP 页面,它连接到我的 MySQL 数据库并提取上表的信息并将其作为 XML 文件返回。
<?php
if(!$dbconnect = mysql_connect('localhost', 'root', 'password')) {
echo "Connection failed to the host 'localhost'.";
exit;
} // if
if (!mysql_select_db('mysampledb')) {
echo "Cannot connect to database 'mysampledb'";
exit;
} // if
$table_id = 'html5';
$query = "SELECT * FROM $table_id";
$dbresult = mysql_query($query, $dbconnect);
// create a new XML document
$doc = new DomDocument('1.0');
// create root node
$root = $doc->createElement('note');
$root = $doc->appendChild($root);
// process one row at a time
while($row = mysql_fetch_assoc($dbresult))
{
// add node for each row
$occ = $doc->createElement($table_id);
$occ = $root->appendChild($occ);
// add a child node for each field
foreach ($row as $fieldname => $fieldvalue)
{
//create child element in xml file
$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);
//add database content into the child element created above
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
}// foreach
}// while
// get completed xml document
$xml_string = $doc->saveXML();
echo $xml_string;
?>
我在一个单独的目录中创建了一个 HTML5 页面,该页面通过单击按钮向上述 PHP 页面发出简单请求,并尝试获取响应并将其显示为警报。
这是 HTML5 页面:-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<button onclick="myFunc()">Click me</button>
<script type="text/javascript">
function myFunc()
{
$.ajax(
{
url:"http://localhost/sample.php"+"?randVar="+Math.random(),
type: "GET",
dataType: "text/xml",
success:function(result)
{
alert(result);
}
});
}
</script>
</body>
</html>
但是当我运行这个页面时,我只能在 IE9 中得到响应。在 Firefox 和 Chrome 中,我看到一个空警报。
在尝试这种方式之前,我也尝试过使用 XMLHttpRequest 对象,但即使这样,我也只能在 IE9 上得到响应。
function myFunc()
{
var xmlhttp, xmlDoc;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
xmlhttp.open("GET","http://localhost/sample.php"+"?randVar="+Math.random(),false);
xmlhttp.send();
xmlDoc=xmlhttp.responseText;
}
catch(e)
{
alert(e.message);
}
alert(xmlDoc);
}
在 Firefox 中,catch 块返回“失败”,在 Chrome 中,警报显示XMLHttpRequest Exception 101。
PS: -
将 HTML 文件保存在与 sample.php 页面相同的 htdocs 文件夹中可以解决问题,但在服务器是不同网络上的单独计算机的现实世界中这是不可能的。所以我不是在寻找这个建议。
在 ajax 调用中,使 async="true" 或 "false" 没有任何区别。
这是 IE9 中的响应:-
萤火虫:-
谁能给我一个解决方案?我非常需要一个。