通过ajax调用echo json_encode()不起作用 [英] echo json_encode() not working via ajax call

查看:55
本文介绍了通过ajax调用echo json_encode()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不知道我在这里想念的是什么.我有这个脚本:

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>

这是我的 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);

那我想念的是什么?我认为代码中没有附加字符串,它在控制台中提供了字符串,而不是json编码的数据.请帮忙!谢谢!

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!

这是控制台中返回的数据.

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

推荐答案

您有三个选择:

  1. $.ajax 中的选项中添加 dataType:'json'.
  2. 在PHP代码中添加 header("Content-type:application/json"); .
  3. 在成功函数中使用 console.log($.parseJSON(data)).
  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.

请注意,如果您还使用了选项1或2,则不应使用选项3.jQuery在前两种情况下会自动解析JSON,并且您将尝试解析其结果,但不会工作.

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.

这篇关于通过ajax调用echo json_encode()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆