我一直在学习一些 ajax 教程,直到完成第一个代码,但是我遇到了错误,因为我对 ajax 不是很熟悉,所以我没有收到错误,我理解这些事情,但是这段代码在他的教程中运行良好但是当我运行它,它会转到最后一个 else 并执行 alert("Error in the end yarr")...... 有人可以帮我吗,谢谢
动态.html
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="practice.js"></script>
</head>
<body onload="process()">
<h2>Ajax!! It Begins<h2>
Enter a muslim name :
<input type="text" id="mname"/>
<div id="show"></div>
</body>
</html>
练习.js
var xmlHttp = createXmlHttpRequestObject(); //xmlHttp --> a main object in Ajax
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){ //when user not using IE
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}
else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("Errorr yrrrrrr!!");
}
else{
return xmlHttp; //because in the first line , it is equal to the function so needs to return
}
}
function process(){ //takes that Communication object(xmlHttp) and sends request to the server
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
name = encodeURIComponent(document.getElementById('mname').value);
xmlHttp.open("GET", "muslims.php?name="+name, true); //if it should be handled asyncrounsly
xmlHttp.onreadystatechange = handleServerResponse; //this handles the server response after you send request to server
xmlHttp.send(null);
}
else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){ //sends back xml code in php file
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){ //200 means communication went normal
document.write("Enters 44");
xmlResponse = xmlHttp.responseXML; //basically xmlResponse is now your xml from php file
xmlDocumentElement = xmlResponse.DocumentElement;
message = xmlDocumentElement.FirstChild.data; //this message will be equal to one of the echos from php file
document.getElementById('show').innerHtml = '<span style="color:red">'+ message + '</span>';
setTimeout('process()',1000);
}
else{
alert("Error in the end yarrrrrrr!!!");
}
}
}
穆斯林.php
<?php
header('Content-type: text/xml');
echo '<?xml version="1.0" encoding:"UTF-8" standalone:"yes" ?>'
echo '<response>'
$name = $_GET['name'];
$namearray = array('Muhammad', 'Ali' , 'Fatima', 'Hassan', 'Hussain');
if(in_array($name,$namearray)){
echo 'Yay!!!! It is a muslim name , whatever';
}
else if($name==''){
echo 'You have to enter some name in the field you dumbass';
}
else{
echo 'Either your name is not muslim or we dont have this name, please dobara hath pair marain';
}
echo '</response>'
?>