dongwu9647
2018-04-12 14:25
浏览 82

php + jquery + ajax获取多个值

I am working with jQuery AJAX. Using an AJAX call I invoke a PHP page. By default it returns a single value to the success function of AJAX. However I want to retrieve multiple data individually. What can I do?

Here's the jQuery code with AJAX , which returns a single value:

function getTime(){
  $.ajax({
    type: "POST",
    url: "test.php",
    data: {
      fd: sdate,
      sd: edate
    },
    dataType: "text",
    success: function(msg) {
      $("#results").text(msg);
    }
  });
};

Test.php:

echo $days;
echo $hours;
echo $minutes;
echo $seconds;

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

我正在使用jQuery AJAX。 使用AJAX调用我调用一个PHP页面。 默认情况下,它会向AJAX的 success 函数返回一个值。 但是我想单独检索多个数据。 我能做什么?

这是带有AJAX的jQuery代码,它返回一个值:

  function getTime(){
 $  .ajax({
 type:“POST”,
 url:“test.php”,
 data:{
 fd:sdate,
 sd:edate 
},
 dataType:“text”,  
 success:function(msg){
 $(“#results”)。text(msg); 
} 
}); 
}; 
   
 
  

Test.php:

  echo $ days; 
echo $ hours; 
echo $ minutes; 
echo $ seconds;  
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongzhuifeng1843 2018-04-12 14:30
    已采纳

    Typically to return multiple responses, the easiest way to do this is to return a json encoded array. Something like the following should work.

    echo json_encode( array(
        "days" => $days,
        "hours" => $hours,
        "minutes" => $minutes,
        "seconds" => $seconds
    ) );
    

    Since your ajax request has dataType: "text" you will need to parse the response to use it with JSON.parse(msg), however if you changed it to dataType: "json" you would not have to do this step as jQuery will try to auto parse it for you.

    打赏 评论
  • dqnqpqv3841 2018-04-12 14:36

    your test.php would be like this

    echo json_encode( array(
        "days" => $days,
        "hours" => $hours,
        "minutes" => $minutes,
        "seconds" => $seconds
    ));
    

    and on ajax success

    success: function(msg) {
        var result = $.parseJSON(msg);
        console.log(result.days)
    }
    
    打赏 评论
  • dongshen9686 2018-04-12 15:05

    The proper way is to use array and encode it in JSON.

     echo json_encode( array(
      "days" => $days;
      "hours" => $hours;
      "minutes" => $minutes;
      "seconds" $seconds;
     )
    );
    

    but you should use the datatype JSON otherwise you have to parse the response like

        var result = $.parseJSON(response);
        console.log(result.days)
    
    打赏 评论

相关推荐 更多相似问题