echo json_encode()无法通过ajax调用工作

I really don't know what i'm missing here. I have this script:

        <script type="text/javascript">
            function ServiceOffer(){
                var service_name  = $('#service_name').val(),
                    dataString = "service="  + service_name;
                    $.ajax({
                        type: "POST",
                        url:  "posted.php",
                        data:dataString,
                        success:function(data){
                            console.log(data);
                        }
                    });
            }

            $(document).ready(function(){   
                ServiceOffer();

                $(document).on('change','#service_name',function(){
                    ServiceOffer();                 
                });     
            });
        </script>

And here is my code for posted.php

    <?php

        $connect = mysql_connect('localhost','root','') or die('Unable to connect'.mysql_error());
        $select = mysql_select_db('hcs',$connect) or die('Unable to select database'.mysql_error());
        $service = $_POST['service'];

        $query = mysql_query("SELECT * FROM serviceoffer WHERE servicename = '$service'");
        $num = mysql_num_rows($query);  

        while($rows = mysql_fetch_array($query)){
            $data[] = $rows;
        }
        echo json_encode($data);

So what i'm missing? I don't think there is a string that is being attached in my code and it gives me string in my console and not json encoded data. Please Help! Thanks!

Edit: Here is the data that is being returned in my console.

enter image description here

You have three options:

  1. Add dataType: 'json' to the options in $.ajax.
  2. Add header("Content-type: application/json"); to the PHP code.
  3. Use console.log($.parseJSON(data)) in the success function.

Note that you shouldn't use option 3 if you've also used options 1 or 2. jQuery automatically parses the JSON in the first two cases, and you'll try to parse the result of that, which won't work.

At a minimum, you should send the appropriate header in PHP, eg

header('Content-type: application/json');
echo json_encode($data);
exit;

You can also set the dataType in jQuery's $.ajax method to specify the expected response type. I also find it easier to send request parameters as object literals (saves having to build URL encoded strings), eg

$.ajax({
    type: 'POST',
    dataType: 'json',
    data: { service: service_name },
    //etc

Update

As shirejedi mentioned, you should initialise $data as an array

$data = array();
while($rows = mysql_fetch_array($query)){
    $data[] = $rows;
}