2017-03-02 57 views
1

我想从PHP返回数组AJAX却是返回null而不是我派回AJAX为什么我的PHP在AJAX调用中返回NULL?

这里的数据是我的代码

的header.php

<?php 
    include_once("obtainData.php"); 
?> 

<!DOCTYPE html> 
<html lang="es"> 
    <head> 
    <meta charset="utf-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <title>AJAX CALL</title> 

    <!-- JQuery --> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    </head> 
    <body> 

的index.php

<?php 
    include_once("header.php"); 
?> 

<div> 
    <h3>AJAX CALL</h3> 
    <p> 
    <?php 
     sendData(); 
    ?> 
    </p> 
</div> 

<?php 
    include_once("footer.php"); 
?> 

footer.php

 <script> 
      $.ajax({ 
       url: "obtainData.php", 
       data: {action: 'sendData'}, 
       type: 'GET', 
       success: function(data) { 
       alert(data); 
       alert("Success"); 
       }, 
       error: function() { 
       alert("Error."); 
       } 
      }); 
     </script> 
    </body> 
</html> 

obtainData.php

<?php 
    if(isset($_POST["action"])){ 
     $action = $_POST['action']; 
     switch($action) { 
      case 'sendData': 
       sendData(); 
       break; 
     } 
    } 

    function sendData(){ 
     $array = []; 

     for($i = 0; $i < 20; $i++){ 
      $array[$i] = "prove"; 
     } 

     echo json_encode($array); 
    } 
?> 

如果我打电话给我的sendData方法在我的嵌入式PHP它显示我的输出,但我无法从AJAX得到它呼叫。

我错过了什么吗?

提前致谢!

+0

变化GET或POST的好 – Raman

回答

3

您在Ajax调用中使用type: 'GET',

而你试图在你的php文件中检索$_POST。这就是为什么什么都得不到。

SO改变type: 'GET',type: 'POST',

+0

......我现在很尴尬。是的,这是问题所在。谢谢! –

2

问题是因为您发送GET请求,但使用$_POST来检索值。结果isset($_POST["action"])总是错误的。

请使用$_GET来检索PHP代码中的值,或更改jQuery以发送POST请求。