S
S
StanleyShilow2018-01-28 12:59:28
JavaScript
StanleyShilow, 2018-01-28 12:59:28

How to pull up a photo using the wall.get method?

Friends, I again went on the path of war and, continuing my study of JS, I came across an inability to load, or rather, it seems to me, to delve into json nesting and pull out a photo from there. The Internet is full of various explanations, but no matter how I use the proposed solutions, it comes out either empty, or an error, or NaN.
The text is pulled up adequately, the date too, but the photo and likes, for example, are not. It seems that I need to specify a fully detailed path to the object, but I ran out of ideas on how to do this.

function getUrl(method, params) {
    if (!method) throw new Error ('отсутствует метод!');
    params = params || {};
    params['access_token'] = '********************************';
    return 'https://api.vk.com/method/' + method + '?&v=4.1&' + $.param(params);
}

$.ajax({
   url: getUrl ('wall.get', {owner_id: -********, count: 100, offset: 2, filter: 'owner', fields:'text, src_big, date'}),
    method: 'GET',
    dataType:'JSONP',
    success: function(data) {
    drawNews(data.response);
    console.log(data);
  }
});

function drawNews(news){
  var html = ('');
  for(var i = 1; i < news.length; i++){
      var n = news[i];
      n.date = new Date(n.date * 1000);
      html += '<div><div style="width:300px; height:auto;"><p>'+ n.text +'</p><p>'+ n.date.toString() +'</p></div><img src="'+ n.src_big + '"></div>';
  }
  $('#news').html(html);
}

Have a nice day, everyone. I'd be grateful if you could clarify what I did wrong...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2018-01-28
@StanleyShilow

Look closely at the JSON returned by wall.get() : the photos there are in the array attachments.
Those. it is necessary to go through these attachments in one more cycle in each post, and if type == 'photo', draw a picture.

function drawNews(news){
  var html = ('');
  for(var i = 1; i < news.length; i++){
      var n = news[i];
      n.date = new Date(n.date * 1000);

      var images = [], tmpl = '<img src="%SRC%" alt="">';
      if( n.attachments) {
        for( var j=0; j<n.attachments.length; j++) {
          if(n.attachments[j].type !== 'photo') continue;
          images.push(
            tmpl.replace('%SRC%', n.attachments[j].photo.photo_130)
          );
        }
      }

      html += '<div><div style="width:300px; height:auto;"><p>'+ n.text +'</p><p>'+ n.date.toString() +'</p></div>' + images.join('') + '</div>';
  }
  $('#news').html(html);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question