AJAX请求中的JavaScript for循环不起作用

时间:2018-01-05 22:12:27

标签: ajax

我对JavaScript for loop for looping有点问题。 这是代码:

if (this.readyState === 4 && this.status === 200)
{
    if(this.response)
    {
        console.log(this.response);
        var data = JSON.parse(this.responseText);
        var output = '';
        console.log(data);
        for(var i=1 ; i <= data.length ; i++)
        {
            console.log('i got here');
            output += '<a href="'+data[i].platform_name+'">'+
                            '<div class="new-prod">' +
                              '<div class="flip">' +
                                  '<div class="front">' +
                                      '<img src="images/'+data[i].picture+'" alt="Image for '+data[i].product_name+'">'+
                                      '<p class="name">'+data[i].product_name+' ('+data[i].platform_name+')</p>'+
                                      '<p class="price">'+data[i].price+' Kč</p>'+
                                   '</div>'+
                                   '<div class="back">'+data[i].description+'</div>'+
                                   '</div>'+
                               '</div>'+
                        '</a>';
        }
        console.log(i);
        document.getElementById('new-container').innerHTML = output;
        document.getElementById('lmbtn').setAttribute('data-offset',parseInt(offset)+8);
    }
    else
    {
        document.getElementById('lmbtn').textContent="Thats all";
    }
}

正如您所看到的,我正在向服务器发出AJAX请求并获取JSON作为响应。 我的代码到达console.log(数据),它将解析的JSON记录到控制台,但由于某种原因,它会跳过for循环。 console.log('我来了');没有记录。最后它记录console.log(i)为1并将容器的innerHTML设置为空字符串。 请原谅我的英语不好,谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

最好在$notificationsEnabled = ( $settings['notificationsEnabled'] == 1); // Cast notification messages to a variable $notificationMessageMsgs = \Config::get('customer_messages.notificationMessageArray'); $numNotificationMessageMsgs = count($notificationMessageMsgs); $notificationMessageSelected = false; // Determine which email subject radio button is checked foreach($notificationMessageMsgs as $index => $msg) { $isSelected = false; if ($settingsForMessages->notification_message == null && $index == 0) { $notificationMessageSelected = true; $isSelected = true; } if($msg['message'] === $settingsForMessages->notification_message){ $isSelected = true; $notificationMessageSelected = true; } if($index == $numNotificationMessageMsgs - 1 && !$notificationMessageSelected){ $isSelected = true; } $notificationMessageRadios[] = array_merge(['selected' => $isSelected], $msg); }循环中使用for(var i=1 ; i <= Object.keys(data).length ; i++)for (var key in data)作为条件。