dongshiliao7990
2018-04-17 05:05
浏览 122

Ajax发布到PHP返回空数组

I need to pass a json object from JS to PHP, and it will pass, but the result is an empty array.

Ajax request in 'adopt.php':

var info = JSON.stringify(filteredArray);
$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: {'info': info},
    success: function(data){
        console.log(data);
    }
});

ajax.php code:

if(isset($_POST['info'])){
    $_SESSION['array'] = $_POST['info'];
}

back in adopt.php, later:

if(isset($_SESSION['array'])){
    $arr = $_SESSION['array'];
    echo "console.log('information: ' + $arr);";
}

in both of the console.logs, it returns an empty object. Does anybody know what could be causing this? (i've tried just passing the json without stringifying it, but it throws a jquery error whenever i do this.)

图片转代码服务由CSDN问答提供 功能建议

我需要将一个json对象从JS传递给PHP,它会传递,但结果是一个空数组 。

'adopt.php'中的Ajax请求:

  var info = JSON.stringify(filteredArray); 
 $ .ajax  ({
 type:'POST',
 url:'ajax.php',
 data:{'info':info},
 success:function(data){
 console.log(data);  
} 
}); 
   
 
 

ajax.php代码:

  if(isset($ _ POST)  ['info'])){
 $ _SESSION ['array'] = $ _POST ['info']; 
} 
   
 
 

回到采用中。 php,稍后:

  if(isset($ _ SESSION ['array'])){
 $ arr = $ _SESSION ['array']; 
 echo“console 两个console.logs中的.log('information:'+ $ arr);“; 
} 
   
 
 

,它返回一个空对象。 有人知道是什么原因引起的吗? (我试过只传递json而不用字符串化它,但每当我这样做时它会抛出一个jquery错误。)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongzice4895 2018-04-17 09:21
    已采纳

    To get the response data from PHP, you need to echo your data to return it to the browser.

    In your ajax.php:

    if (isset($_POST['info'])) {
        $_SESSION['array'] = $_POST['info'];
        echo json_encode(['result' => $_SESSION['array']]);
    }
    
    点赞 打赏 评论
  • dongzou3751 2018-04-17 05:13

    Try below code i think you miss return ajax response

    adopt.php

    <script>
    var info = JSON.stringify(filteredArray);
    
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {info: info},
        success: function(data){
            console.log(data);
        }
    });
    </script>
    

    ajax.php

    if (isset($_POST['info'])) {
        $_SESSION['array'] = $_POST['info'];
        echo json_encode(["result" => "success"]);
    }
    
    点赞 打赏 评论
  • dongshao8566 2018-04-17 06:21

    Your ajax.php is not returning any data.To get data at the time of success you need to echo the data you want to display on success of your ajax.

    点赞 打赏 评论

相关推荐 更多相似问题