dsutuyxe088689
2014-07-08 11:10 浏览 49

Ajax - 为什么我不能从外部PHP文件中检索数据?

I've been trying to create a simple grade calculator app with ajax functionality. The ajax seems to be working quite nicely, however the separate PHP file I've created 'response.php' is not GET-ting the data from the form. So it is just echoing out 'Uh oh'.

I'm not sure what I'm doing wrong here and I've been going over my code for a while. Can anyone help?

<!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 compiled and minified CSS -->
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/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.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    <script>

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

    </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="button" 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.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

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

  </body>
</html>

response.php

<?php 

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

        if (isset($currentGrade, $targetGrade, $finalWorth)) {
            echo $currentGrade;
            echo $targetGrade;
            echo $finalWorth;
        } else {
            echo 'Uh oh!';
        }

        // if (empty($currentGrade, $targetGrade, $finalWorth)) {
        //     echo 'Nothing...';
        // } else {

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



?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答 默认 最新

  • 已采纳
    dongweihuai5601 dongweihuai5601 2014-07-08 12:04

    As far as I am aware you can't retrieve the data because, using the verb (GET) for your call, requires a querystring appended to the target url, this way:

    xhr.open("GET","response.php?key1=value1&key2=value2...etc..."); 
    

    However In my opinion would be better to use the POST verb:

    xhr.open("POST","response.php", true);
    

    then set a valid request header like:

    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    

    collect the params (your new sendAjax function):

    function sendAjax() {
    
        var values = [];
        var form = document.getElementById("gradeForm");
    
        for (var i = 0, l = form.length; i < l; i++) 
        {
            if(form[i].type === "text")
            {
                values.push(form[i].name +"="+ form[i].value);
            }
        };
    
        var params = values.join("&"); 
    
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
        xhr.send(params);
    
        document.getElementById('gradeForm').style.display = 'none';
    }
    

    Now you can retrieve the data in the response.php page, via the superglobal $_POST

    点赞 评论 复制链接分享
  • dougao9864 dougao9864 2014-07-08 11:19

    This is how you do ajax request, without jQuery. You can re-purpose this for your own need.

    I made this work as single page script:

    test.php

    <?php
    
    // Handle GET Ajax Request
    if (count($_GET))
    {
        print_r($_GET);
        exit();
    }
    
    ?>
    
    <script type="text/javascript">
    
    // helper function - http://stackoverflow.com/a/8567149/2332336
    function loadXMLDoc(targetUrl, resultDiv) {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 ) {
               if(xmlhttp.status == 200){
                   document.getElementById(resultDiv).innerHTML = xmlhttp.responseText;
               }
               else if(xmlhttp.status == 400) {
                  alert('There was an error 400')
               }
               else {
                   alert('something else other than 200 was returned')
               }
            }
        }
        xmlhttp.open("GET", targetUrl, true);
        xmlhttp.send();
    }
    
    // usage
    loadXMLDoc('test.php?a=1&b=2', 'result');
    
    </script>
    
    <div id="result"></div>
    
    点赞 评论 复制链接分享
  • dtdvbf37193 dtdvbf37193 2014-07-08 11:19

    The reason response.php is unable to get the data from the form is that your AJAX isn't sending the data from the form. Unlike a form submit, AJAX won't automatically send the form - you need to set the parameters explicitly.

    点赞 评论 复制链接分享

相关推荐