dptpn06684 2014-04-11 13:03
浏览 48
已采纳

使用each()打印数组时出现jquery ajax()问题

In my code I am returning an php array containing records of 7 Students. With jquery ajax() I want to print these records on success function.

DB table Students

+---------------------------+
| name | fathername | Email |
+---------------------------+

submit.php

$query=mysql_query("SELECT * from Students LIMIT 0,6");

   $row= array();
   $row=mysql_fetch_array($query);
   return json_encode($row);

index.php

<script>
    $(function(){
        $("#form1").submit(function(event){
            event.preventDefault();

            $.ajax({
                    url:'submit.php',
                    type:'GET',
                    data:$(this).serialize(),
                    success:function(result){
                $.each(result,function(){
                $('.StudentName').text(result["name"]);
                $('.FatherName').text(result["fathername"]);
                $('.Email').text(result["email"]);
                    });

                    }
            });
        });
    });
</script>

<div class="StudentName"></div>
<div class="FatherName"></div>
<div class="Email"></div>

EDIT I tried to return only 1 result from php and it works i.e.

echo json_encode(mysql_fetch_array($query));

When I return all 6 records the jquery function dont execute i.e.

while($result=mysql_fetch_array($query))
{
echo json_encode($result);
}
  • 写回答

4条回答 默认 最新

  • dongquan6030 2014-04-11 13:05
    关注

    There's difference between PHP arrays and JS arrays, you can't simply pass the PHP array to your javascript, so instead you should first json_encode it and send it to js.

    This will convert your PHP array to JSON array, eg:

     array(3) {
      [0]=>
        string(3) "foo"
      [2]=>
       string(3) "baz"
      [3]=>
       string(5) "blong"
    }
    

    to

    string(33) "{"0":"foo","2":"baz","3":"blong"}"
    

    So try -

    return json_encode($row);
    

    and then when you catch the response, use parseJSON:

    result = jQuery.parseJSON(result);
    $.each(result,function(){
       $('.StudentName').text(result.name);
       $('.FatherName').text(result.fathername);
       $('.Email').text(result.email);
    });
    

    Edit:

    Another thing, instead of return json_encode($row); write echo json_encode($row);

    Edit 2

    (to send all 6 records)

    $final = array();
    while($result=mysql_fetch_array($query))
    {
        array_push($final,$result);
    }
    echo $final;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大