从ajax调用成功内部访问变量 [英] Access a variable from inside ajax call success

查看:43
本文介绍了从ajax调用成功内部访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的js文件中包含以下内容:

I have the following in my js file:

var highestNumb;
$.ajax({
          url: 'https://api.m.hostelworld.com/1.5/properties/'+propID+'/?update-cache=true', 
          dataType: 'json', 
          headers: {
            "Accept-Language": lang 
          },
          success: function(json) { 
            var numb = 0;
            for (var key in json.rating) {
                numb = Math.max(numb, json.rating[key]);
            }
            highestNumb = numb;
            return highestNumb;

          }, cache: false
});
var enH3 = 'Fellow travellers have rated this property ' + highestNumb + ' out of 100.',
    deH3 = 'Gäste haben das Hostel mit ' + highestNumb + ' von 100 Punkten bewertet. ',
    frH3 = 'Les autres voyageurs ont classé cette propriété ' + highestNumb + ' sur 100',
    esH3 = 'Otros viajeros han puntuado este alojamiento con u ' + highestNumb + ' sobre 100.',
    itH3 = "I tuoi compagni di viaggio hanno recensito questa struttura " + highestNumb + " su 100",
    brH3 = 'Hóspedes anteriores avaliaram esta propriedade em ' + highestNumb + ' de 100.',
    ptH3 = 'Hóspedes anteriores avaliaram esta propriedade em ' + highestNumb + ' de 100.',
    koH3 = '직접 여행한 숙박객들은 이 호스텔을 10점 만점 중 XX점 주셨습니다. ';

每次在下面的变量翻译中传递"highestNumber"时,我都变得不确定.

I am getting undefined every time I pass "highestNumber" in the variables translation below.

我以错误的方式访问变量吗?

Am I accessing the variable in the wrong way?

推荐答案

您应该在成功函数中调用另一个函数,例如.setVars(highestNumb)并将设置enH3,deH3等变量的代码放入该函数中.

You should in your success function call another function, eg. setVars(highestNumb) and put your code that sets enH3, deH3 etc. variables in that function.

success: function(json) { 
   //your code
   setVars(numb);
}

function setVars(highestNumb)
{
    enH3 = 'Fellow travellers have rated this property ' + highestNumb + ' out of 100.';
    //....
}

这篇关于从ajax调用成功内部访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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