AJAX Javascript中的变量范围 [英] Javascript variable scope inside ajax function

查看:123
本文介绍了AJAX Javascript中的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能是一个愚蠢的问题,我知道JS范围的问题是对SO极为常见,但你能可能是好心帮我这个反正。

i know this is probably a stupid question and i know js scope questions are extremely common on SO, but could you possibly be kind enough to help me with this one anyway.

下面是我的功能:

function checkOpen(storeData) {
if (storeData.menu === 'true') {

    var offerImgPath = '/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color'+ Brand.styleColour + '/v3/',
        offer1,
        offer2;

    cafeTabContent = '<p>Cafe/Restaurant facilities are available in this store.</p>';
    cafeTabContent += '<p class="menu_link"><a href="/store_menus/menu.pdf" target="_blank">Click here to download a menu</a></p>';

    if (Brand.storeLocatorSettings.cafeOffersOn === true) {

        $.ajax({
            url : Arcadia.Brand.storeLocatorSettings.offersPageURL,
            success : function(data) {
                var offerContainer = $(data).find('#basic_story_content');
                offer1 = offerContainer.children(':first-child').attr('src');
                offer2 = offerContainer.children(':last-child').attr('src');
            }
        });

        console.log(offer1);

        cafeTabContent += '<p>Current offers:</p>';
        cafeTabContent += '<p class="offer_graphic"><img src="' + offer1+ '" alt="Offer 1" /></p>';
        cafeTabContent += '<p class="offer_graphic"><img src="' + offer2+ '" alt="Offer 2" /></p>';
    }

    return cafeTabContent;
} else {
    return false;
}
};

我遇到的问题是,尽管offer1和放大器; offer2被阿贾克斯成功定义在函数外,该函数中应用的值不被保留外,因此CONSOLE.LOG(offer1)返回undefined,而不是图像路径。我知道这是一个范围内的问题,而且它真的是烦我。任何帮助将大大AP preciated。

The problem that i am having is that despite the fact that offer1 & offer2 are defined outside the ajax success function, the values applied within this function are not being maintained outside hence console.log(offer1) returns undefined instead of the image path. I know this is a scope question, and it is really bugging me. Any help would be greatly appreciated.

推荐答案

在阿贾克斯A表示异步。
所以控制台语句执行前的实际数据返回。这意味着成功后返回值被分配到offer1和offer2,但你已经印它控制台之前。
试试这个

In Ajax A means Asynchronous.
So console statement is executed before actual data is returned. It means after successful return value is assigned to offer1 and offer2 but you have printed it on console before that.
Try this

  $.ajax({
            url : Arcadia.Brand.storeLocatorSettings.offersPageURL,
            success : function(data) {
                var offerContainer = $(data).find('#basic_story_content');
                offer1 = offerContainer.children(':first-child').attr('src');
                offer2 = offerContainer.children(':last-child').attr('src');
        console.log(offer1);
        console.log(offer2);
            }
        });

这篇关于AJAX Javascript中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆