D
D
Dmitriy50232018-07-09 13:41:28
JavaScript
Dmitriy5023, 2018-07-09 13:41:28

How to fix error when getting url of images (wall.get vk api method)?

I'm trying to display images from a group. When displaying the url on the page, an error occurs. Uncaught TypeError: Cannot read property 'attachments' of undefined although urls are visible in the console.

$('#load').on('click', loadFriends);

function getUrl(method,params) {
    if (!method) throw new Error('Вы не указали метод!');
    params = params || {};
    params['access_token'] = 'здесь токен';
    return 'https://api.vk.com/method/' + method + '?' + $.param(params) + '&v=5.80';
}

function sendRequest(method,params,func) {
    $.ajax({
        url: getUrl(method,params),
        headers: {'Access-Control-Allow-Origin': '*'},
        method: 'GET',
        dataType: 'JSONP',
        success: func
    }); 
}

function loadFriends() {
    sendRequest('wall.get', {domain:'tattoogenius' ,offset: 0, count:4}, function (data) {
        var html = '';
        for (var i = 0; i < data.response.count; i++) {    
            if (typeof data.response.items[i].attachments != 'undefined') {    
                sizeCol = data.response.items[i].attachments[0].photo.sizes.length - 1;
                url = data.response.items[i].attachments[0].photo.sizes[sizeCol].url;
                console.log(url);
                html += '<p>' + url + '</p>';
        }   
    }
    $('.photos').html(html);
}); 
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Panteleev, 2018-07-12
@s_panteleev

function loadFriends() {
    sendRequest('wall.get', {domain:'tattoogenius' ,offset: 0, count:4}, function (data) {
      var html = '';
      data.response.items.map(function(item) {
        item.attachments[0].photo.sizes.map(function(picture) {
          var url = picture.url;
          html += '<p>' + url + '</p>';
        })
      });

      $('.photos').html(html);
    });
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question