douwen3836 2016-04-20 11:18
浏览 40
已采纳

未捕获的TypeError:不能在jquery / json中使用'in'运算符

I create a json in php like this:

$details= array();
$ret = array();

for($i=0;$i<3;$i++) { $details["name"] = "name".$i;  $ret[] = $details;}

And then return it to a jquery ajax:

echo json_encode($ret,JSON_UNESCAPED_UNICODE);
die();

In jQuery ajax:

$.ajax({
    url: "index2.php?id=upload",
    type: "POST",
    data:  new FormData($("#form")[0]),
    contentType: false,
    cache: false,
    processData:false,
    returnType:"json",
    success: function(data)
    {
        console.log('names:'+JSON.stringify(data));
        $.each(data, function(i) 
        { 
            console.log('name:'+data[i]['name']);
         }
    },

first console log prints,but second: I get this error:

jquery-2.2.3.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"name":"name1"},{"name":"name2"},{"name":"name3"}]

Also I try

$.each(JSON.parse(data), function(i) 
                { ..}

but I print empty:

name:undefined

  • 写回答

2条回答 默认 最新

  • douceng7070 2016-04-20 11:36
    关注

    When the javascript converts your json string into a javascript data type it will be an array of objects like this

    Array
    (
        [0] => stdClass Object
            (
                [name] => name0
            )
    
        [1] => stdClass Object
            (
                [name] => name1
            )
    
        [2] => stdClass Object
            (
                [name] => name2
            )
    
    )
    

    So your javascript should be

    Also returnType:"json" should be dateType:"json" as far as I know there is not such parameter as returnType:

       $.ajax({
            url: "index2.php?id=upload",
            type: "POST",
            data:  new FormData($("#form")[0]),
            contentType: false,
            cache: false,
            processData:false,
            dateType:"json",
            success: function(data)
            {
                console.log('names:'+JSON.stringify(data));
                $.each(data, function(i,v) 
                { 
                    console.log('name:'+v.name);
                }
            },
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32 函数调用问题
  • ¥15 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动
  • ¥15 大一C语言期末考试,求帮助🙏🙏