开发者

JS bug: input field repeated with xmlhttp response text

This is a follow up of another question I asked last night. My problem now is not that the script doesn't works, but that I'm getting some very strange repeat of an HTML input element when my xmlhttprequest object returns the response text. Here's the code:

<!DOCTYPE HTML>

<?php

    if(!empty($_GET['uName']))
    {
        $r = mysql_connect("localhost", "root", "pass") or die("Couldn't connect to db");
        mysql_select_db("db", $r) or die ("Couldn't select db");
        $q = mysql_query("select * from users where uName = '{$_GET['uName']}'") or die("Couldn't query table");
        $data = mysql_fetch_assoc($q);
        mysql_close(开发者_如何学JAVA$r);
    }

?>

<html>

<head>

</head>

<body>

<form>

    <input type="text" name="fUName" onchange="ShowUser(fUName.value);" value="name" style="width:125px;">

</form>

<div id="display"><?php print "ID = {$data['id']}"; ?></div>

</body>

</html>

<script type='text/javascript'>

function ShowUser(name)
{
    if(name.length == 0)
    {
        document.getElementById("display").innerHTML = "Please enter a username to check";
        return;
    }
    if(window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function()
    {
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            document.getElementById("display").innerHTML = xmlhttp.responseText;
        }
    };

    xmlhttp.open("GET", "index.php?uName=" + name, true);
    xmlhttp.send();

}

</script>

Here's the strange problem:

JS bug: input field repeated with xmlhttp response text

There should only be one input field, and is orginally, however when I enter text into it and it loses focus, the JS is triggered and also prints out another input field.

Please ignore the bad practice of PHP, JS and HTML/CSS in one script, this was supposed to be a quick test that has turned for the worse :)

I'm baffled!

Thanks for any help.


The problem lies in the fact that all of your code is in one page. Consider this: you load up index.php. After it's all displaying then you call this same page again (for your AJAX request) so you're essentially saying "Hey, I want you to try and load this page again," hence why you're ending up with duplicate fields.

Try separating out your files in to something like index.php and getuser.php or something of the sort.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜