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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置