最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is XMLHttpRequest readystate not equal to 4? - Stack Overflow

programmeradmin1浏览0评论

I'm learning AJAX for the first time and I'm trying to create a simple application that calculates the grade a person needs to get on their final exam based on their previous assessment results.

The user inputs their grades into the form and then using ajax I calculate the response in response.php which should then be output in the callback function in the div with ajax as its id.

For some reason the xhr.readystate property is never reaching 4 so the response is never generated. Can anybody see what I'm doing wrong?

Please bear in mind I'm only learning...

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Grade Calculator</title>

    <!-- Latest piled and minified CSS -->
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn/bootstrap/3.2.0/css/bootstrap.min.css">

    <link rel="stylesheet" href="style.css">

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src=".7.2/html5shiv.min.js"></script>
      <script src=".4.2/respond.min.js"></script>
    <![endif]-->

    <script>

        function sendAjax() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    document.getElementById('ajax').innerHTML = xhr.responseText;
                } else {
                    document.getElementById('ajax').innerHTML = document.write('There was a problem');
                }
            };
            xhr.open("GET","response.php"); 
                xhr.send();
                document.getElementById('gradeForm').style.display = "none";
                document.write(xhr.readyState);
        }

    </script>


  </head>

  <body>

    <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
          </ul>
        </div>
      </div>
    </div>

    <div class="container">

      <div class="starter-template">
        <h1>Bootstrap starter template</h1><br>

        <form action="index.php" method="get" id="gradeForm">
            <div class="form-group">
                <label for="currentGrade">What is your current Grade</label>
                <input type="text" name="currentGrade"><br>
            </div>
            <div class="form-group">
                <label for="targetGrade">What is your target Grade</label>
                <input type="text" name="targetGrade"><br>
            </div>
            <div class="form-group">
                <label for="finalWorth">What is your final worth?</label>
                <input type="text" name="finalWorth"><br>
            </div>
            <button type="submit" class="btn btn-default" onclick="sendAjax()">Submit</button>
        </form>

        <div id="ajax">

        </div>

      </div>

    </div><!-- /.container -->


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src=".11.1/jquery.min.js"></script>

    <!-- Latest piled and minified JavaScript -->
    <script src="//maxcdn.bootstrapcdn/bootstrap/3.2.0/js/bootstrap.min.js"></script>

  </body>
</html>

Here is response.php

<?php 

        $currentGrade = $_GET['currentGrade'];
        $targetGrade = $_GET['targetGrade'];
        $finalWorth = $_GET['finalWorth'];

        $neededMark = $currentGrade - $targetGrade;
        $neededMark = $neededMark / $finalWorth;
        $neededMark = $neededMark * 100;
        $neededMark = round($neededMark);

        if(isset($currentGrade, $targetGrade,$finalWorth)) {
            echo $neededMark;
        }

?>

I'm learning AJAX for the first time and I'm trying to create a simple application that calculates the grade a person needs to get on their final exam based on their previous assessment results.

The user inputs their grades into the form and then using ajax I calculate the response in response.php which should then be output in the callback function in the div with ajax as its id.

For some reason the xhr.readystate property is never reaching 4 so the response is never generated. Can anybody see what I'm doing wrong?

Please bear in mind I'm only learning...

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Grade Calculator</title>

    <!-- Latest piled and minified CSS -->
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn./bootstrap/3.2.0/css/bootstrap.min.css">

    <link rel="stylesheet" href="style.css">

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn./html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn./respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    <script>

        function sendAjax() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    document.getElementById('ajax').innerHTML = xhr.responseText;
                } else {
                    document.getElementById('ajax').innerHTML = document.write('There was a problem');
                }
            };
            xhr.open("GET","response.php"); 
                xhr.send();
                document.getElementById('gradeForm').style.display = "none";
                document.write(xhr.readyState);
        }

    </script>


  </head>

  <body>

    <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Project name</a>
        </div>
        <div class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
          </ul>
        </div>
      </div>
    </div>

    <div class="container">

      <div class="starter-template">
        <h1>Bootstrap starter template</h1><br>

        <form action="index.php" method="get" id="gradeForm">
            <div class="form-group">
                <label for="currentGrade">What is your current Grade</label>
                <input type="text" name="currentGrade"><br>
            </div>
            <div class="form-group">
                <label for="targetGrade">What is your target Grade</label>
                <input type="text" name="targetGrade"><br>
            </div>
            <div class="form-group">
                <label for="finalWorth">What is your final worth?</label>
                <input type="text" name="finalWorth"><br>
            </div>
            <button type="submit" class="btn btn-default" onclick="sendAjax()">Submit</button>
        </form>

        <div id="ajax">

        </div>

      </div>

    </div><!-- /.container -->


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    <!-- Latest piled and minified JavaScript -->
    <script src="//maxcdn.bootstrapcdn./bootstrap/3.2.0/js/bootstrap.min.js"></script>

  </body>
</html>

Here is response.php

<?php 

        $currentGrade = $_GET['currentGrade'];
        $targetGrade = $_GET['targetGrade'];
        $finalWorth = $_GET['finalWorth'];

        $neededMark = $currentGrade - $targetGrade;
        $neededMark = $neededMark / $finalWorth;
        $neededMark = $neededMark * 100;
        $neededMark = round($neededMark);

        if(isset($currentGrade, $targetGrade,$finalWorth)) {
            echo $neededMark;
        }

?>
Share Improve this question asked Jul 8, 2014 at 8:46 chapchap 1,8595 gold badges27 silver badges39 bronze badges 2
  • 1 I guess submitting the form will reload the page. Try to prevent default action of the submit button, or use button type="button". – Teemu Commented Jul 8, 2014 at 8:55
  • 2 Further to the ments of others, document.write is evil and should be avoided - especially in cases like this. It has the effect of nuking the body of your document - which means that when readyState does equal 4, the element with the id of ajax has been overwritten with "There was a problem" (n times). document.getElementById('ajax').innerHTML = xhr.responseText; is okay, document.write(xhr.readyState); really isn't okay and document.getElementById('ajax').innerHTML = document.write('There was a problem'); is more than a little horrifying! – enhzflep Commented Jul 8, 2014 at 9:46
Add a ment  | 

3 Answers 3

Reset to default 5

The correct order of operations is:

  1. construct
  2. open
  3. set handler
  4. send

You are doing them in the order 1324, which is incorrect and therefore likely to not behave as expected.

Put things in the right order, see if that works :)

EDIT: Additionally, remove all document.write calls. They will not work with any asynchronous operation and will almost certainly break things.

EDIT EDIT: Also, <button type="submit" class="btn btn-default" onclick="sendAjax()"> - this should be type="button", otherwise your form will be submitted and it will look like it did nothing.

doesn't look like you are sending any parameters in your ajax request so response.php is not GETting any data...

if it were xhr.open("GET","response.php?param1=value1&param2=value2"); etc you should get something

Only one small change is required In form division make instead of submit. Because on submit the forms behaviour is different as pared to just a button click

发布评论

评论列表(0)

  1. 暂无评论