无法在ajax成功函数中显示数组值

时间:2017-11-22 15:15:07

标签: php jquery arrays ajax

      $.ajax({
                type: "GET",
                url: 'http://localhost/abc/all-data.php',
                data: {
                    data1: "1"},
                    success: function(response)
                           {
                        alert(response);
                        }          
            });
            return false; 

我希望在ajax的成功函数中逐一显示数组的每个元素,目前我将所有元素都添加到gether中

这是我的PHP代码

$i=0;
while($row = mysqli_fetch_assoc( $qry )){

$temp[$i]['c_n'] = $row['c_name'];
$temp[$i]['j_t'] = $row['Job_Title'];
$temp[$i]['des'] = $row['description'];
$temp[$i]['req'] = $row['requirments'];
$temp[$i]['dat'] = $row['posted'];

$i++;
}
$data = array('temp'=> $temp);
echo JSON_encode($temp);

我很感激你的帮助

3 个答案:

答案 0 :(得分:2)

你可能在你的成功函数中使用这样的东西:

   response.temp.forEach(function(element){
         console.log(element.c_n) ;
         console.log(element.j_t) ;
         console.log(element.des) ;
         console.log(element.req) ; 
         console.log(element.dat) ;
    });

答案 1 :(得分:1)

在您的成功功能中,您需要json解析您的回复

var data = JSON.parse(response);

您可以访问您的数据: data['temp']

如果您希望自动将您的响应解析为json,可以设置如下的ajax设置:

$.ajaxSetup ({
   contentType: "application/json",
   dataType: 'json'
});

然后你不再需要调用JSON.parse了。

答案 2 :(得分:0)

您的代码:

$i=0;  while($row = mysqli_fetch_assoc($qry)){
  $temp[$i]['c_n'] = $row['c_name'];
  $temp[$i]['j_t'] = $row['Job_Title'];
  $temp[$i]['des'] = $row['description'];
  $temp[$i]['req'] = $row['requirments'];
  $temp[$i]['dat'] = $row['posted'];
  $i++;
}      $data = array('temp'=> $temp);   echo JSON_encode($temp);

请将最后一行更改为 return JSON_encode($data);

希望这可以帮助你:)

相关问题