Ajax请求超出范围

时间:2014-07-30 11:36:57

标签: jquery ajax

$(function(){
var imgClass = $('.caruselWrap').find('img');  
imgClass.eq(1).addClass('pro');
var hasPro = $('.caruselWrap').find('img.pro');
var count = 3; // "position" of images, security for not breaking out
var imgLoaded = 3;
var flag = true;
var arr = [];

var ajax = function() {
    var url = 'gallery/img' + count + '.jpg';

    var request = new XMLHttpRequest();
    request.open('GET', url);
    request.onreadystatechange = function() {
        if ((request.readyState === 4) && (request.status === 200)) {
            arr[imgLoaded] = '<img class="addedImg" src="' + url + '" />';
            $('.caruselWrap').append(arr[imgLoaded]);
            flag = true;

            $('.addedImg').click(function(){ 
                var img = $(this);
                check(img);

                console.log("count: " + count);
                console.log("images loaded: " + imgLoaded);
                console.log(flag);
            })

        }
    }
    request.send();
    imgLoaded++;
}

var change = function(string) {
    if((string == "left") && (count >= 3)) {
        hasPro.prev().addClass('pro').next().removeAttr('class');
    } else if (string == "right") {
        hasPro.next().addClass('pro').prev().removeAttr('class');
    }
}

var check = function(a){
    var add = imgClass.outerWidth(true);
    hasPro = $('.caruselWrap').find('img.pro');

    if(hasPro.index() > a.index()){
        if(count > 3) {
            --count;
            change("left");

            $('.caruselWrap').animate({
                left: '+=' + add,
            })
        }
    } else if(hasPro.index() < a.index()) {
        if(flag) {
            ++count;
            if(imgLoaded < count) {
                ajax();
            }
            change("right");            
            $('.caruselWrap').animate({
                left: '-=' + add,
            })
        }
    } else {
        console.log("Center image clicked! Full screen view");
    }
}

$('.caruselWrap img').click(function(){ 
    var img = $(this);
    check(img);

    console.log("count: " + count);
    console.log("images loaded: " + imgLoaded);

})

})

嗨,我需要修改代码的建议。主要假设是旋转木马有3个图像可见,中心图像总是有“亲”类。 这里的主要问题是,通过ajax加载图像我会超出范围,图像可用于图库。它停在下一个(不存在的)元素/ img文件夹中。

Click for preview

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

您正在使用Jquery,然后使用jquery版本的ajax。看看

     // get ajax request

     $.get('url',{param:value,param2:value},function(response){
         // do your stuff with response;
     }); 

     // post ajax request
     $.post('url',{param:value,param2:value},function(response){
         // do your stuff with response;
     }); 

   // another version
     $.ajax({
         url:'',
         method:'POST/GET',
         success: function(response){
                      // do your stuff with response;
        }
     });