JavaScript / AJAX在显示图片时会说“未定义”

时间:2013-05-24 03:12:07

标签: php javascript javascript-events pdo

在我的注册页面上,我正在设置它,以便当有人在用户名框中输入用户名时,如果用户名不存在,它将显示绿色复选标记,如果用户名不存在,则显示红色“X”这个账户名已经存在。当页面加载时(body标签是),它没有出现图片,它会出现“undefined”这个词。

JavaScript代码:

var xmlHttp = createXmlHttpRequestObject();

//Create object for function
function createXmlHttpRequestObject(){
    var xmlHttp;

    //Check if IE
    if(window.ActiveXObject){
        try{
            //Setting variable equal to object for IE
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(e){
            //Can't set variable equal to something
            xmlHttp = false;
        }
    }else{
    //Anything not IE
        try{
            //Want to use this object if not IE
            xmlHttp = new XMLHttpRequest;
        }catch(e){
            //Can't set variable equal to something
            xmlHttp = false;
        }
    }
    //If couldn't set object
    if(!xmlHttp){
        //Tell people that JS couldn't create the object (new XMLHttpRequest or ActiveXObject)
        alert("Couldn't create an object with JavaScript!");
    }else{
        //Return object
        return xmlHttp;
    }
}

//Use this attribute for body tag: <body onload="process()">
function process(){
/*readyState:
0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready
*/
    try{
        //Check if ready to communicate
        if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
            //<input type="text" id="userInput" /> relates to this
            //Set variable to value they typed in
            username = encodeURIComponent(document.getElementById("register_name").value);

            //Creates request to send to server
            //Need PHP file, GET would be in PHP file, also can be POST, etc.
            xmlHttp.open("POST","functions/check_used.php",true);

            //Doing something to make it pretend like it's a form, for POST
            xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

            //Handle server response when server responds to the request
            xmlHttp.onreadystatechange = handleServerResponse;

            //Send request (this is used for POST, use null when using GET)
            xmlHttp.send("username="+username);
        }else{
            //Not ready to communicate, wait for 1 second and try again
            setTimeout('process()',1000);
        }
    }catch(e){
        //Something doesn't work, tell them what happened
        alert(e.toString());
    }
}

//When response received, tells what to do with it
function handleServerResponse(){
//Response done communicating
    if(xmlHttp.readyState==4){
        //Communication went OK
        if(xmlHttp.status==200){
            //Put response into variable
            xmlResponse = xmlHttp.responseXML;

            //Get document element
            xmlDocumentElement = xmlResponse.documentElement;

            //Get data from XML file
            message = xmlDocumentElement.firstChild.data;

            //Access document, put it in element on page, innerHTML is stuff shown on webpage
            document.getElementById("checkedUser").innerHTML = message;

            //Pause 1 second before communicating with server again
            setTimeout('process()',1000);
        }else{
            //There was an error with data
            alert('Something went wrong!');
        }
    }
}

在注册页面上,我有一个输入框,旁边有div:

<input type="text" id="register_name" name="username" /><div id="checkedUser"></div>

最后,我有一个发布到的PHP文件:

<?php
require_once('../includes/db.php');
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<username>';
    $check_username = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username");
    $check_username->bindValue(":username",$_POST['username'],PDO::PARAM_STR);
    $check_username->execute();
    $check_username = $check_username->fetch();

    if($check_username[0] == 0){
        echo '<img src="images/success.png" />';
    }else{
        echo '<img src="images/error.png" />';
    }
echo '</username>';
?>

我尝试过排查它,但我无法弄清楚出了什么问题。

2 个答案:

答案 0 :(得分:2)

在输入中侦听按键,并在输入更改时检查用户名:

$(function() {
    $('#register_name').keyup(function() {
        $.ajax({
            type: 'POST',
            url : 'functions/check_used.php',
            data: {username : this.value},
            success: function(result) {
               $('#checkedUser').html(result);
            }
        });
    });
});

并且无需返回XML:

<?php
    require_once('../includes/db.php');
    header('Content-Type: text/html');

    $check_username = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username");
    $check_username->bindValue(":username",$_POST['username'],PDO::PARAM_STR);
    $check_username->execute();
    $check_username = $check_username->fetch();

    if($check_username[0] == 0){
        echo '<img src="images/success.png" />';
    }else{
        echo '<img src="images/error.png" />';
    }
?>

答案 1 :(得分:2)

  if(xmlHttp.readyState==0 || xmlHttp.readyState==4){ 

应该是

  if(xmlHttp.readyState== 4 && xmlHttp.status == 200){