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.

    评论

报告相同问题?