Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
简单的AJAX/PHP问题,但解释很长_Php_Ajax - Fatal编程技术网

简单的AJAX/PHP问题,但解释很长

简单的AJAX/PHP问题,但解释很长,php,ajax,Php,Ajax,我刚开始读这本书——《AJAX和PHP第二版》,第一个例子我就失败了。我很确定代码与书中所示的一样,但当我在错误控制台(Mozzila 6.0)中运行index.htm时,我得到了以下信息:“xmlResponse为空,我不知道发生了什么,但我真的不想一开始就放弃,所以我将遍历所有3个文件,希望有人能告诉我问题所在。 以下是index.htm: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ww

我刚开始读这本书——《AJAX和PHP第二版》,第一个例子我就失败了。我很确定代码与书中所示的一样,但当我在错误控制台(Mozzila 6.0)中运行index.htm时,我得到了以下信息:“xmlResponse为空,我不知道发生了什么,但我真的不想一开始就放弃,所以我将遍历所有3个文件,希望有人能告诉我问题所在。 以下是index.htm:

<!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>
<title>AJAX with PHP, 2nd Edition: Quickstart</title>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload="process();">
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" ></div>
</body>
</html>

AJAX与PHP,第二版:快速入门
服务器想知道您的姓名:
以下是quickstart.js:

// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
// stores the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer 6 or older
if(window.ActiveXObject)
{
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else
{
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process(name)
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(
document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send();
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
// callback function executed when a message is received from the
//server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed
//successfully
if (xmlHttp.status == 200)
{
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML
//structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// display the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage
+ '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else
{
alert("There was a problem accessing the server: " +
xmlHttp.statusText);
        }
    }
}
//存储对XMLHttpRequest对象的引用
var xmlHttp=createXmlHttpRequestObject();
//检索XMLHttpRequest对象
函数createXmlHttpRequestObject()
{
//存储对XMLHttpRequest对象的引用
var-xmlHttp;
//如果运行Internet Explorer 6或更早版本
if(window.ActiveXObject)
{
试一试{
xmlHttp=新的ActiveXObject(“Microsoft.xmlHttp”);
}
捕获(e){
xmlHttp=false;
}
}
//如果运行Mozilla或其他浏览器
其他的
{
试一试{
xmlHttp=新的XMLHttpRequest();
}
捕获(e){
xmlHttp=false;
}
}
//返回创建的对象或显示错误消息
如果(!xmlHttp)
警报(“创建XMLHttpRequest对象时出错。”);
其他的
返回xmlHttp;
}
//使用XMLHttpRequest对象发出异步HTTP请求
函数进程(名称)
{
//仅当xmlHttp对象不忙时才继续
if(xmlHttp.readyState==4 | | xmlHttp.readyState==0)
{
//检索用户在表单上键入的名称
name=encodeURIComponent(
document.getElementById(“myName”).value);
//从服务器执行quickstart.php页面
open(“GET”,“quickstart.php?name=“+name,true”);
//定义处理服务器响应的方法
xmlHttp.onreadystatechange=handleServerResponse;
//发出服务器请求
xmlHttp.send();
}
其他的
//如果连接忙,请在一秒钟后重试
setTimeout('process()',1000);
}
//从接收到消息时执行的回调函数
//服务器
函数handleServerResponse()
{
//仅当事务已完成时才向前移动
if(xmlHttp.readyState==4)
{
//状态为200表示事务已完成
//成功地
if(xmlHttp.status==200)
{
//提取从服务器检索到的XML
xmlResponse=xmlHttp.responseXML;
//获取XML的文档元素(根元素)
//结构
xmlDocumentElement=xmlResponse.documentElement;
//获取文本消息,该消息位于
//文档元素的
helloMessage=xmlDocumentElement.firstChild.data;
//显示从服务器接收的数据
document.getElementById(“divMessage”).innerHTML=
''你好消息
+ '';
//重新启动序列
setTimeout('process()',1000);
}
//HTTP状态不同于200表示错误
其他的
{
警报(“访问服务器时出现问题:”+
xmlHttp.statusText);
}
}
}
最后是quickstart.php:

<?php
// we'll generate XML output
header('Content-Type: text/xml');
// generate XML header
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
// create the <response> element
echo '<response>';
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don\'t know you!';
// close the <response> element
echo '</response>';
?>

提前感谢!
Leron

所有这些看起来都是正确的。PHP脚本的宿主在哪里?在本地安装的Apache上,或者在您有权访问的服务器上?在Firefox中,您可以安装难以置信的Firebug插件,进入脚本选项卡,查看请求返回的确切内容。不管它是什么,Fx都不会将其识别为XML(因此xmlResponse成员为空)。

所有这些看起来都是正确的。PHP脚本的宿主在哪里?在本地安装的Apache上,或者在您有权访问的服务器上?在Firefox中,您可以安装难以置信的Firebug插件,进入脚本选项卡,查看请求返回的确切内容。不管它是什么,Fx都无法将其识别为XML(因此xmlResponse成员为空)。

我发现您的代码存在一些问题。提到其中一些

  • 您正在body onload上调用
    进程()。这意味着,当DOM就绪时,浏览器调用
    process()
    函数。在我看来,这不是你想要的。相反,要有一个按钮,它通过
    onclick
    事件调用此流程函数。比如:

    <button onclick="process('YODA');return false;">Click Me!</button>
这是你的JS节/文件

function myProcess(){
    process(encodeURIComponent(document.getElementById('myName').value));
}
  • 在进程函数中不要有
    document.getElementById(..)
    。它破坏了传递参数“name”的全部目的
我想请你使用一个非常好的浏览器,比如Mozilla Firefox或Google Chrome(因为你似乎在代码中给了IE6一个优先权,至少看起来是这样!)。Chrome有一个很棒的检视窗口。一旦你掌握了窍门,你几乎会爱上它。是的!;-)

我建议您使用jQuery(www.jQuery.com)之类的库来实现ajax。让你的生活更轻松!:-)

编辑

我建议您执行以下步骤,因为您希望让这段代码正常工作

  • 首先打开url
    [BASE-url]/quickstate.php?name=YODA
    。如果一切正常,您应该看到对AJAX调用的响应XML。如果不是,则PHP文件(或服务器的一些设置)存在一些问题,而不是其他任何问题。我觉得这一步不成问题

  • 接下来,加载页面后,在文本框中键入“YODA”,在浏览器的URL框中键入:
    javascript:process(“”)
    。这应该调用具有ajax调用的函数。你可以在firebug的数据传输部分保留一个标签(我不知道确切的名称,但它是Google Chrome中的“网络”部分)。您可以分析发送到PHP脚本的头,以及从服务器返回给您的响应(包括HTTP错误代码)。我也觉得这不会是个问题

导致问题的原因是:页面的DOM被加载。一旦DOM就绪,就会进行AJAX调用。这意味着AJAX请求甚至在您在文本框中键入任何内容之前发出。因此,发送到服务器的请求的

function myProcess(){
    process(encodeURIComponent(document.getElementById('myName').value));
}