【问题标题】:cannot display array values in ajax success function无法在 ajax 成功函数中显示数组值
【发布时间】:2017-11-22 15:15:07
【问题描述】:
      $.ajax({
                type: "GET",
                url: 'http://localhost/abc/all-data.php',
                data: {
                    data1: "1"},
                    success: function(response)
                           {
                        alert(response);
                        }          
            });
            return false; 

我想在 ajax 的成功函数中一个一个地显示数组的每个元素,目前我将所有元素聚集在一起

这是我的 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);

非常感谢您的帮助

【问题讨论】:

    标签: php jquery arrays ajax


    【解决方案1】:

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

       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) ;
        });
    

    【讨论】:

      【解决方案2】:

      在你的成功函数中,你需要json解析你的响应

      var data = JSON.parse(response);
      

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

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

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

      那么你就不需要再调用 JSON.parse 了。

      【讨论】:

      • 当我使用 JSON.parse 和 alert(data['temp']);它显示未定义
      • @Ahmad 请实际向我们展示您使用的代码。简单地说某事不起作用,或者显示未定义是没有用的,因为您可能没有正确使用该方法
      • console.log(data) 打印什么?
      • 成功:function(response) { var data = JSON.parse(response);警报(数据['temp']); //console.log(数据); }
      • @Ahmad 好的,console.log(response) 呢?
      【解决方案3】:

      您的代码:

      $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);

      希望对你有帮助:)

      【讨论】:

        猜你喜欢
        • 2021-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-01
        • 2016-06-04
        • 1970-01-01
        • 2014-05-18
        相关资源
        最近更新 更多