从ajax调用成功

时间:2016-04-13 10:52:27

标签: javascript ajax

我的js文件中有以下内容:

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”时,我都会被定义。

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

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:-1)

请输入async:false

var highestNumb; $就({           url:'https://api.m.hostelworld.com/1.5/properties/'+ propID +'/?update-cache = true',           dataType:'json',           异步:假的,           标题:{             “接受语言”:郎           },           成功:function(json){             var numb = 0;             for(json.rating中的var键){                 numb = Math.max(numb,json.rating [key]);             }             highestNumb =麻木;             return highestNumb;

      }, cache: false

});