Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 07.11.2015, 17:18
Интересующийся
Отправить личное сообщение для tybys Посмотреть профиль Найти все сообщения от tybys
 
Регистрация: 25.02.2011
Сообщений: 10

Смещение цикла, обход массива исключая дубли, полный ликбез
Добрый день, подскажите как лучше всего решить проблему. До меня к сожалению не доходит, не так часто пишу на js.

Имеется динамический массив (запросы к vk.api), по domready делаю 1 запрос, чтобы оперативно обрабатывать массив и показывать его содержимое. Далее, например по клику на тычку "more" я совершаю еще запросы и дописываю в массив новые значения.

Но у меня, каждый раз по клику на тычку "more" обрабатываются и дублируются данные

Сейчас пробовал с методом push (до этого был concat :18 строчка), чтобы у меня был всегда набор из "актуальных" данных, но у меня руки из {_o_}

пример в песочнице http://plnkr.co/edit/wSWybiotn3xYGIfroa3g

Буду рад любым объяснениям

var url = "https://api.vkontakte.ru/method/wall.get?domain=adme";
var offset = 0;
var postsCount = 0;
var result = [];

function newPost() {
    $.ajax({
        url: url,
        dataType: "jsonp",
        data: {
            count: 10,
            offset: offset
        },
        success: function(data) {
            var posts = data.response;

            postsCount = posts.shift();
            result.push(posts);
            offset += 10;

            parsePostsRaw();
        }
    });
}

function parsePostsRaw() {
    for (var i=0; i < result.length; i++) {
        for (var j = 0; j < result[i].length; j++) {
            var current = result[i][j].id;
            var text = $("<p>", {'class': 'text', text: result[i][j].text})
            var img = result[i][j].attachment.photo.src;
            var id = result[i][j].id;
            var li = $("<li>", {}).html("<p>"+result[i][j].text+"</p>"+"<img src='"+img+"' />"+"<span>"+id+"</span>");

            $('#resultText').append(li);
        }
    }
}

window.addEventListener("DOMContentLoaded", function () {
    newPost();

    $('#more').click(function () {
        newPost();
    });
});
Ответить с цитированием
  #2 (permalink)  
Старый 07.11.2015, 18:46
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,103

tybys,
нажать Ещё ? внизу
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <style type="text/css">
   #resultText{
     display: flex;
      flex-wrap: wrap;
   }

 #resultText >  li{
     display: inline-block;
    word-wrap: break-word;
    width: 340px;
    list-style-type: none;
    background: #D2B48C none repeat scroll 0 0;
    border: 1px solid #ffcc00;
    border-radius: 16px;
    box-sizing: border-box;
    overflow: hidden;
    vertical-align: middle;
    padding: 20px;
    margin: 5px;
   }
   #more{

    color: #FFFFFF;
    font-size: 48px;
    font-weight: normal;
     display: block;
    line-height: 48px;
    margin: 0 auto;
    width: 100%;


   }

 #resultText >  li.end{
  text-align:  center;
  background: black;
  color: white;
   }

   .al-pic {
    border-radius: 15px;
    display: block;
    height: 180px;
    margin: 0 0 9px;
    width: 300px;
}
 a.al-title {
    color: #FFFFFF;
    font-size: 20px;
    font-weight: normal;
    line-height: 28px;
    margin: 0 0 6px;
}
 .al-title {
    font-size: 22px;
    font-weight: normal;
    line-height: 28px;
    margin: 0 0 6px;
}


.cssload-container {
	position: relative;
	z-index: 4;
	margin: 0 auto;
    display: none;
	width: 166px;
	height: 78px;
	list-style: none;
	border: 2px solid rgba(0,0,0,0.4);
	border-radius: 39px;
}


.cssload-loader{
	position: absolute;
	z-index: 3;
	margin: 0 auto;
	left: -40px;
	right: 0;
	top: 50%;
	margin-top: -29px;
	width: 97px;
	height: 58px;
	list-style: none;
}

ul.cssload-loader li{
	background-color: rgb(255, 255, 255);
	width: 10px;
	height: 10px;
	float: right;
	margin-right: 5px !important;
	box-shadow: 0px 19px 10px rgba(0,0,0,0.2);
		-o-box-shadow: 0px 19px 10px rgba(0,0,0,0.2);
		-ms-box-shadow: 0px 19px 10px rgba(0,0,0,0.2);
		-webkit-box-shadow: 0px 19px 10px rgba(0,0,0,0.2);
		-moz-box-shadow: 0px 19px 10px rgba(0,0,0,0.2);
}
.cssload-loader li:first-child{
	animation: cssload-loadbars 1.15s cubic-bezier(0.645,0.045,0.355,1) infinite 0s;
		-o-animation: cssload-loadbars 1.15s cubic-bezier(0.645,0.045,0.355,1) infinite 0s;
		-ms-animation: cssload-loadbars 1.15s cubic-bezier(0.645,0.045,0.355,1) infinite 0s;
		-webkit-animation: cssload-loadbars 1.15s cubic-bezier(0.645,0.045,0.355,1) infinite 0s;
		-moz-animation: cssload-loadbars 1.15s cubic-bezier(0.645,0.045,0.355,1) infinite 0s;
}
.cssload-loader li:nth-child(2){
	animation: cssload-loadbars 1.15s ease-in-out infinite -0.23s;
		-o-animation: cssload-loadbars 1.15s ease-in-out infinite -0.23s;
		-ms-animation: cssload-loadbars 1.15s ease-in-out infinite -0.23s;
		-webkit-animation: cssload-loadbars 1.15s ease-in-out infinite -0.23s;
		-moz-animation: cssload-loadbars 1.15s ease-in-out infinite -0.23s;
}
.cssload-loader li:nth-child(3){
	animation: cssload-loadbars 1.15s ease-in-out infinite -0.46s;
		-o-animation: cssload-loadbars 1.15s ease-in-out infinite -0.46s;
		-ms-animation: cssload-loadbars 1.15s ease-in-out infinite -0.46s;
		-webkit-animation: cssload-loadbars 1.15s ease-in-out infinite -0.46s;
		-moz-animation: cssload-loadbars 1.15s ease-in-out infinite -0.46s;
}
.cssload-loader li:nth-child(4){
	animation: cssload-loadbars 1.15s ease-in-out infinite -0.69s;
		-o-animation: cssload-loadbars 1.15s ease-in-out infinite -0.69s;
		-ms-animation: cssload-loadbars 1.15s ease-in-out infinite -0.69s;
		-webkit-animation: cssload-loadbars 1.15s ease-in-out infinite -0.69s;
		-moz-animation: cssload-loadbars 1.15s ease-in-out infinite -0.69s;
}
.cssload-loader li:nth-child(5){
	animation: cssload-loadbars 1.15s ease-in-out infinite -0.92s;
		-o-animation: cssload-loadbars 1.15s ease-in-out infinite -0.92s;
		-ms-animation: cssload-loadbars 1.15s ease-in-out infinite -0.92s;
		-webkit-animation: cssload-loadbars 1.15s ease-in-out infinite -0.92s;
		-moz-animation: cssload-loadbars 1.15s ease-in-out infinite -0.92s;
}
.cssload-loader li:nth-child(6){
	animation: cssload-loadbars 1.15s ease-in-out infinite -1.15s;
		-o-animation: cssload-loadbars 1.15s ease-in-out infinite -1.15s;
		-ms-animation: cssload-loadbars 1.15s ease-in-out infinite -1.15s;
		-webkit-animation: cssload-loadbars 1.15s ease-in-out infinite -1.15s;
		-moz-animation: cssload-loadbars 1.15s ease-in-out infinite -1.15s;
}



@keyframes cssload-loadbars {
	0%{
		height: 10px;
		margin-top: 24px;
	}
	50%{
		height:49px;
		margin-top: 0px;
	}
	100%{
		height: 10px;
		margin-top: 24px;
	}
}

@-o-keyframes cssload-loadbars {
	0%{
		height: 10px;
		margin-top: 24px;
	}
	50%{
		height:49px;
		margin-top: 0px;
	}
	100%{
		height: 10px;
		margin-top: 24px;
	}
}

@-ms-keyframes cssload-loadbars {
	0%{
		height: 10px;
		margin-top: 24px;
	}
	50%{
		height:49px;
		margin-top: 0px;
	}
	100%{
		height: 10px;
		margin-top: 24px;
	}
}

@-webkit-keyframes cssload-loadbars {
	0%{
		height: 10px;
		margin-top: 24px;
	}
	50%{
		height:49px;
		margin-top: 0px;
	}
	100%{
		height: 10px;
		margin-top: 24px;
	}
}

@-moz-keyframes cssload-loadbars {
	0%{
		height: 10px;
		margin-top: 24px;
	}
	50%{
		height:49px;
		margin-top: 0px;
	}
	100%{
		height: 10px;
		margin-top: 24px;
	}
}
    </style>
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script>
$(window).load(function () {
    $.fn.scrollTo = function (speed, easing, callback) {
        $('body, html').animate({
            scrollTop: this.offset().top
        }, speed, easing, callback);
        return this;
    };
function rand(min, max, integer) {
  var r = Math.random() * (max - min) + min;
  return integer ? r|0 : r;
};
var url = "https://api.vkontakte.ru/method/wall.get?domain=adme";
var offset = 0;
var postsCount = 0;
var old = {};
function newPost() {
    $.ajax({
        url: url,
        dataType: "jsonp",
        data: {
            count: 10,
            offset: rand(1, postsCount, true)
        },
        success: function(data) {
            var posts = data.response;
            postsCount = posts.shift();
            offset += 10;
            parse(posts);
        }
    });
}

function parse(data) {
    var liEnd = $(".end"), current = liEnd.prev(), n = 0;
    $.each(data, function(indx, el) {
        var id = el.id,
            attach = el.attachments, img, a;
        if (!old[id] && attach && attach.length > 1) {
            old[id] = true;
            var li = $("<li/>");
            $.each(attach, function(indx, el) {
                var photo = el.photo;
                if (photo) {
                    var src = photo.src_big;
                    if (src && !img) {
                            img = $("<img/>", {
                            src: src,
                            width: "300",
                            height: "180",
                            "class": "al-pic"
                        });
                        img.appendTo(li)
                    }
                }
                var link = el.link;
                if (link) {
                      a = $("<a/>", {
                        "class": "al-title",
                        href: link.url,
                        text: link.title
                    });
                    a.appendTo(li);
                    var h = $("<h3/>", {
                        "class": "al-title",
                        html: link.description
                    });
                    h.appendTo(li)
                }
            });
          img && a && li.insertBefore(liEnd) && n++
        }
    });
    !n && newPost();
    n && $('.cssload-container').hide() && $('#more').show()
    current.length && current.next().scrollTo(1E3)
};
newPost();
$('#more').click(function (event) {
        event.preventDefault();
        $('#more').hide();
        $('.cssload-container').show()
        newPost();
    });

}); </script>
</head>
<body>
    <table id="TableA"></table>
    <div id="DivA"></div>
    <ul id="resultText"><li class="end"><a href="#" id="more"  class="al-title">Ещё ?</a><h3 class="al-title">Мне нужно больше интересных статей</h3>
  <div class="cssload-container">
	<ul class="cssload-loader">
		<li></li><li></li><li></li><li></li><li></li><li></li>
	</ul>
</div>
    </li></ul>

</body>
</html>

Последний раз редактировалось рони, 08.11.2015 в 05:05.
Ответить с цитированием
  #3 (permalink)  
Старый 08.11.2015, 10:32
Интересующийся
Отправить личное сообщение для tybys Посмотреть профиль Найти все сообщения от tybys
 
Регистрация: 25.02.2011
Сообщений: 10

рони, спасибо вам за помощь, я ваш предыдущий вариант разобрал и понял, этот тоже разберу сегодня.

Я его чуть-чуть изменил только, академического интереса ради хочу без jquery обойтись, или оставить только айджекс, ибо мне непонятно как проще и без большого кол-ва кода написать кросдоменный запрос
Ответить с цитированием
  #4 (permalink)  
Старый 08.11.2015, 11:21
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,103

tybys,
структуру незнаю json (где-то есть информация?), но
данные в json неполные, поэтому сделал фильтрацию на наличие ссылки и одного фото -- и если в пришедшем ответе таких нет или пришли повторные данные идёт новый запрос
строки 298 и 299.
ещё бы ввести в обьект old -- длину и проверять чтоб неуйти в бесконечный запрос, когда все данные выберутся. (их у вас много, но на всякий)
первый запрос с нуля, остальные случайно из общего числа ... ориентировался что первый элемент, что это и есть длина всех данных.
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск