dregvw1801 2013-12-12 00:57
浏览 314
已采纳

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

  • 写回答

2条回答 默认 最新

  • drrvnbwle80177811 2013-12-12 01:02
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。