如何在同一个文件中检索通过AJAX发送到PHP的数据?

时间:2017-04-28 04:26:15

标签: php ajax

通过使用AJAX方法GET将数据发送到php文件,如何在PHP文件中检索数据?

AJAX和PHP在同一个文件中

 <script>
   var xhr = new XMLHttpRequest();
   xhr.open("get","kal.php?id=5",true);
   xhr.send();
 </script>
 <?php
   echo "result is : ".$_REQUEST['id'];
  ?>

它表示未定义的索引:id 并且$_REQUEST['id']的值也是空的。

4 个答案:

答案 0 :(得分:2)

将XHR请求发送到同一页面时,您可能需要特别注意处理请求的PHP代码。例如,如果在处理请求的代码之前在页面上生成了任何输出,那么您可能希望从发送回javascript回调函数的响应中丢弃该输出。通常要执行此操作,我会在请求处理代码的开头使用ob_clean(),然后使用exit确保响应终止

<?php
    if( $_SERVER['REQUEST_METHOD']=='GET' ){

        /* 
            listen for XMLHttpRequest requests
            ----------------------------------
            By testing for the existence of a particular header in the request
            you can ensure that a simple pageload with querystring does not
            trigger the id to be displayed.
            The ajax function sets the 'X-Requested-With' header and PHP reads this
            as 'HTTP_X_REQUESTED_WITH'
        */
        if( isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] == 'XMLHttpRequest' && !empty( $_GET['id'] ) ) {

            /* discard any previous output */
            ob_clean();

            /* send the response to the javascript client */
            header('Content-Type: text/html');
            exit( 'Response='.$_GET['id'] );
        }
    }
?>
<html>
    <head>
        <title>XHR to same page</title>
    </head>
    <body>
        <div id='msg'></div>
        <script>

            var id=23;

            var xhr = new XMLHttpRequest();

            /* Only display the response if the request succeeds */
            xhr.onreadystatechange=function(r){
                if( xhr.readyState==4 && xhr.status==200 ){
                    document.getElementById('msg').innerHTML=xhr.response;
                }
            };
            /*
                As the request is to the same page you only require the
                query part of the url
            */
            xhr.open( "GET", "?id="+id, true );
            /*
                set some typical headers, including the important 'X-Requested-With' header
            */
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
            xhr.send();
        </script>
    </body>
</html>

答案 1 :(得分:0)

当第一次加载页面时$_REQUEST['id']未定义,因此错误,请使用isset()来阻止它。

注意,当发出AJAX请求时,响应将再次成为Javascript代码。尝试:

if(isset($_REQUEST['id'])) {
    echo "result is : ".$_REQUEST['id'];
} else {
    ?>
  <script>
     var xhr = new XMLHttpRequest();
     xhr.open("get","kal.php?id=5",true);
     xhr.send();
  </script>
    <?php
}

答案 2 :(得分:0)

由于您的页面未刷新/重新加载,因此只能使用js更新内容。来自ajax的响应数据将包含php页面回声/显示的所有内容。因此,您可以使用其他变量来处理ajax请求。

if(isset($_REQUEST['id']) && isset($_REQUEST['ajax']) && $_REQUEST['ajax'] === true) {
    echo "result is : ".$_REQUEST['id'];
    exit(); // the remaining part will not be returned to the ajax response
} else {
?>
<script>
     var xhr = new XMLHttpRequest();
     xhr.open("get","kal.php?id=5",true);
     xhr.send();

    //write the code to update html on receiving ajax response text
</script>
<?php

}

答案 3 :(得分:0)

首次加载页面时,ajax尚未发送请求,因此您将获得undefined index!需要通过isset进行检查,并且您尝试在同一页面中显示,因此请通过XML响应替换当前的html内容!!

<script>
   var xhr = new XMLHttpRequest();
   xhr.open("get","kal.php?id=5",true);
   xhr.send();
   xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    document.body.innerHTML = xhr.responseText;
                }
            }
 </script>
 <?php    
    if(isset($_REQUEST['id'])) {
      echo "result is : ".$_REQUEST['id'];
    }
  ?>
相关问题