简体   繁体   中英

using Ajax and Javascript - executing both if/else statements

Hi im new here so I hope I did this right.. I'm reading the Ajax for Dummies book (read the php one years ago and it was great so giving this one a shot) and I'm stuck on the first real Ajax program.. It took me forever to get it to actually find the text file but while attempting to find out just where the problem was in the program I noticed an issue that I don't understand.

At one point it checks to see if readyState == 4 AND status == 200 and if that's false then it displays the alert message of "nope" -- it always alerts "nope" as well as executes the other part of the if statement.. why? (listed below is the only code i've got so far - no other files that could be calling the function) if I take the "else" statement out it works fine but this could be a problem for me later on and I want to know why it's doing it... thanks a lot!

<!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" xml:lang="en" lang="en">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Ajax at work</title>
<script language = "JavaScript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) 
{
    XMLHttpRequestObject = new XMLHttpRequest();
} 
else if (window.ActiveXObject) 
{
    XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}

function getData(dataSource, divID)
{
    if(XMLHttpRequestObject) 
    {
        var obj = document.getElementById(divID);
        XMLHttpRequestObject.open("GET", dataSource, true);
        XMLHttpRequestObject.onreadystatechange = function()
        {
            if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
            {
                obj.innerHTML = XMLHttpRequestObject.responseText;
            } 
            else 
            {
                alert("nope");
            }
        }
        XMLHttpRequestObject.send(null);
    }
}
</script>
</head>
<body>
    <H1>Fetching data with Ajax</H1>
    <form>
        <input type="button" value="submit" onclick="getData('http://localhost/AV/data.txt', 'targetDiv')">
    </form>
    <div id="targetDiv">
        <p>The fetched data will go here.</p>
    </div>
</body>
</html>

In order to get to 4 , the readyState has to go through 0 , 1 , 2 and 3 . Each time it will fail your if statement - after all, that's why we test for it.

You should do something like:

if( this.readyState != 4) return;
if( this.status == 200) { /* do something with this.responseText */ }
else { /* handle error condition with this.status and this.statusText */ }

Note the use of this - it's better to use the keyword, just in case you later use the variable for something else, you avoid closure problems.

EDIT: And another thing, you should move your new XMLHttpRequest code etc. inside the function that uses it - not all browsers are happy with reusing the same object for multiple requests.

You mentioned in a comment that you're working with a seven-year-old Ajax book. Things have changed a lot in the last seven years. If you're just getting started with this client-side stuff, you would probably do yourself a favor by tossing that book out and taking a more modern approach.

For one thing, there are excellent JavaScript libraries such as jQuery that will take care of many of these details for you. With jQuery, that complicated XMLHttpRequest code can be replaced with a simpler $.ajax() call, or depending on what you're doing, an even simpler $.get() , $.post() , or $.getJSON() call.

Also, recommended modern practice is to not set up your event handler in an onclick attribute, but to use JavaScript code to do it.

So, you would change this line of HTML code:

<input type="button" value="submit"
    onclick="getData('http://localhost/AV/data.txt', 'targetDiv')">

to:

<input type="button" value="submit" id="testButton">

and replace your entire block of JavaScript code with:

$(document).ready( function() {

    $('#testButton').on( 'click', function() {
        $('#targetDiv').load( 'http://localhost/AV/data.txt' );
    });

    $.ajaxError( function( jqXHR, textStatus, errorThrown ) {
        alert( errorThrown );
    });
});

Or, for sake of illustration, another way to code it, using $.ajax() and a getData() function similar to your original:

$(document).ready( function() {
    $('#testButton').on( 'click', function() {
        getData( 'http://localhost/AV/data.txt', '#targetDiv' );
    });
});

function getData( url, target ) {
    $.ajax( url, {
        dataType: 'html',
        success: function( data ) {
            $(target).html( data );
        },
        error: function( jqXHR, textStatus, errorThrown ) {
            alert( errorThrown );
        }
    });
}

Another reason to avoid a seven-year-old Ajax book: If my guess is right, when the book moves past downloading simple HTML as in this example and starts downloading raw data that you'll manipulate in JavaScript, it probably recommends using XML for this data. (XML, of course is the "X" in AJAX.)

However, XML is a terrible way to do this if you're generating the data on your server. In PHP, it's just as easy to generate JSON data instead of XML, and JSON is much easier and faster to work with in JavaScript.

Other libraries you should check out for your JavaScript coding are Underscore.js or its newer sibling Lo-Dash . These libraries have a wonderful variety of utility functions that make all sorts of coding tasks easier.

Also, whether you decide to explore any of these libraries or code "bare metal" JavaScript, please be sure to get familiar with the developer tools that are available in most browsers now. My favorite is the Chrome DevTools .

One other thing; you don't need that complicated XHTML stuff any more:

<!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" xml:lang="en" lang="en">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

You can replace all of that with:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

It's better to configure your server to specify the charset in the Content-Type header; then you won't need the <meta> tag here.

And you don't need the language in the script tag, just use <script> .

Finally, if I may offer one suggestion on coding style… Even if you prefer putting the opening curly brace on its own line:

function foo()
{
    alert( 'bar' );
}

I do not recommend doing that in JavaScript. Instead, use this style:

function foo() {
    alert( 'bar' );
}

The reason is that if you use the former style, you will eventually do this:

function foo()
{
    // Return an object - or does it???
    return
    {
        a: 'b',
        c: 'd'
    }
}

You'll need to put the return and the curly brace after it on the same line for that to work, because of JavaScript's automatic semicolon insertion. Since you have to do it there, you may as well be consistent and write all your code that way:

function foo() {
    // Return an object - or does it???
    return {
        a: 'b',
        c: 'd'
    }
}

I know coding style is a personal preference, but you'll find that most JavaScript developers follow this curly brace convention for this reason, even if they otherwise prefer a different style in other languages.

Please Try This Code Then You Will Get Your Answer.

function getData(dataSource, divID)
{
if(XMLHttpRequestObject)
{
var obj = document.getElementById(divID);

XMLHttpRequestObject.open("GET", dataSource, true);
XMLHttpRequestObject.send(null);
XMLHttpRequestObject.onreadystatechange = function()
{
alert('Ready State:- ' +XMLHttpRequestObject.readyState + '\\n' + 'Status:- ' + XMLHttpRequestObject.status);
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
obj.innerHTML = XMLHttpRequestObject.responseText;
}
else
{
alert("nope");
}
}

}
}

For Further Reference Visit This Link:- All About XMLHTTPRequest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM