weixin_33675507 2016-02-13 22:37 采纳率: 0%
浏览 38

Ajax Json While循环

Hi i im trying to get a value from a database and display it as a link in my navigation bar but i haven't been very successfull.

Start Off with my JQuery

 <script>
         $(document).ready(function(){
              $.ajax({
                    type: 'GET',
                    data: {loadpage: 'table'},
                    url: 'addtable.php',
                    success: function(data){    

                        $('.navbar ul').append('<li><a href="#" class="table">'+THE-PHP-ARRAY I WANT TO SHOW+'</a></li>');
                    } 
                }); //ajax request
             });
    </script>

addtable.php

$query = "SELECT * FROM Menus WHERE menuCreator = '".$_SESSION['U_ID']."'";

$result = mysqli_query($con, $query);
$index=0;
while($row = $result->fetch_array()){

    $index++;
    $data = array(

        $index=>$row['menuName']
    );

    echo json_encode($data);

}

I tried alot of stuff. If i change my dataType to json it doesnt work at all. I tried to put it in an $.each() loop still nothing works. If i go to addtable.php it displays

{"1":"Breakfast"}{"2":"Book Fair"}

which is the correct values in my database

Im sorry if it wasn't too clear im 15 and i only do this between school any help will be greatly appreciated Thanks in advance

  • 写回答

2条回答 默认 最新

  • weixin_33690963 2016-02-13 22:43
    关注

    json_encode outputs a complete JSON text, but outputting it inside a loop you are outputting a bunch of JSON texts butting up against each other. The result isn't a valid, single JSON text.

    Put $data into an array.

    Encode that array as JSON after the loop has finished.

    Then you'll need to loop over that array (data) when it gets converted to JavaScript.

    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助