无法在ajax成功返回时更改图像onChange函数

时间:2015-12-04 03:11:20

标签: javascript jquery ajax

您好我是这个javavascript / ajax的新手。我正在尝试创建一个下拉列表,通过不同的选项动态更改图像,如此Fiddle所示,但更改功能似乎不起作用。

我确保我能够从pictureList获取数据,但图片来源并没有成功地改变。

 $('#selectVariant').change(function () {     
    var sku = $('#selectVariant :selected').val();
    var sessionId="<?php echo $sessionId; ?>";
    var dataString='sku='+ sku +'&sessionId='+sessionId;
    $.ajax({
        type:"post",
        url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
        data:dataString,
        cache:false,
        dataType: "JSON",
        success: function(data){
        var pictureList = {};

        //example of my data list
        //var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
        //'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
        //};

        $.each(data.productVariantImages,function(i, productVariantImages){
            pictureList[data.sku] = this.imagePath;
        });
        console.log(pictureList);

        $('.content img').attr({"src":[pictureList[this.value]]}); 
        }
    });
        return false;
});

然而,当我在ajax帖子之外测试它时,它能够运行。

1 个答案:

答案 0 :(得分:1)

this的实例是ajax成功函数范围的变化。

在这一行中$('.content img').attr({"src":[pictureList[this.value]]}); this 不是selectVariant元素的实例。

通常的做法是声明变量that并在其他范围内使用该变量。尝试以下代码。

$('#selectVariant').change(function () {     
    var sku = $('#selectVariant :selected').val();
    var sessionId="<?php echo $sessionId; ?>";
    var dataString='sku='+ sku +'&sessionId='+sessionId;
    var that = this;
    $.ajax({
        type:"post",
        url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
        data:dataString,
        cache:false,
        dataType: "JSON",
        success: function(data){
        var pictureList = {};

        //example of my data list
        //var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
        //'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
        //};

        $.each(data.productVariantImages,function(i, productVariantImages){
            pictureList[data.sku] = this.imagePath;
        });
        console.log(pictureList);

        $('.content img').attr({"src":[pictureList[that.value]]}); 
        }
    });
        return false;
});