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

时间:2014-07-08 11:10:16

标签: php ajax

我一直在尝试使用ajax功能创建一个简单的成绩计算器应用。 ajax似乎运行得很好,但是我创建的单独的PHP文件' response.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 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 个答案:

答案 0 :(得分:2)

response.php无法从表单中获取数据的原因是您的AJAX没有从表单发送数据。与表单提交不同,AJAX不会自动发送表单 - 您需要明确设置参数。

答案 1 :(得分:2)

据我所知,您无法检索数据,因为使用动词(GET)进行调用时,需要在目标网址后附加查询字符串,这样:

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

但是在我看来,最好使用POST动词:

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

然后设置一个有效的请求标题,如:

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

收集params(你的新sendAjax函数):

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';
}

现在,您可以通过超级全球response.php

$_POST页面中检索数据

答案 2 :(得分:0)

这是你在没有jQuery的情况下执行ajax请求的方法。您可以根据自己的需要重新定位。

我将这项工作视为单页脚本:

<强> 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>