Jquery - 未捕获的类型错误:无法使用“in"运算符来搜索“324"

2022-01-04 00:00:00 jquery php javascript ajax yii

我正在尝试通过 ajax 发送 Get 请求,并以 html 格式输出服务器返回的 json 数据.

I'm trying to send a Get request by ajax and output json data that is returned by server in html.

但是,我遇到了这个错误.

But, I got this error.

Uncaught TypeError: Cannot use 'in' operator to search for '324' in 
[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]

这是我通过ajax向php文件发送Get请求的代码.当我使用 $.each 方法时,它得到了我在上面显示的错误.

This is my code that sends a Get request to php file by ajax. When I use $.each method, it get the error that I showed in the above.

parentCat.on('change', function(e){
    parentCatId = $(this).val();

    $.get(
        'index.php?r=admin/post/ajax',
        {"parentCatId":parentCatId},
        function(data){                     
            $.each(data, function(key, value){
                console.log(key + ":" + value)
            })
        }
    )

})

这是我的PHP代码,以json格式返回查询结果.

This is my PHP code that returns query result in json format.

public function actionAjax(){

    $parentCatId=$_GET['parentCatId'];

        $catData = Category::getTargetCategoryData($parentCatId);

        echo CJSON::encode($catData);
        Yii::app()->end();

}

这个php输出的json数据是这样的.

json data outputted by this php is like this.

[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]

有人知道如何解决这个问题吗?

Anyone knows how to fix this problem?

请帮帮我.提前致谢:)

Please help me out. Thanks in advance :)

推荐答案

您有一个 JSON 字符串,而不是一个对象.告诉 jQuery 您希望得到 JSON 响应,它会为您解析它.要么使用 $.getJSON 而不是 $.get,或将 dataType 参数传递给 $.get:

You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get:

$.get(
    'index.php?r=admin/post/ajax',
    {"parentCatId":parentCatId},
    function(data){                     
        $.each(data, function(key, value){
            console.log(key + ":" + value)
        })
    },
    'json'
);

相关文章