2013-12-25 3 views
0

это моя часть кода:возвращения ответа от вызова AJAX для другой функции

$("#edit-field-order-borispol-und").change(foo);   
function foo() { 
var result; 
var customerid = $("#edit-field-order-customer-und").val(); 
    $.ajax({ 
     type: 'GET', 
     url: '/ops', 
     data: {'customerid': customerid}, 
     success: function(response) { 
      result = response.borispol; 
      alert(response.borispol);// this alerts the info that i NEED... 
     } 
    }); 
return result; 
} 
foo(function(result) { 
    alert(result+' it works'); // cant make it to work... 
    // code that depends on 'result' 
}); 

Я проверил это: How do I return the response from an asynchronous call?

и до сих пор ... Я не могу понять, что это неправильно. Пожалуйста, помогите, я новичок в jquery ...

+1

Ajax - асинхронный.! –

ответ

0

Если вы хотите, чтобы ваш текущий код начал работать, попробуйте добавить свойство async:false в $.ajax. и вместо

foo(function(result) { 
    alert(result+' it works'); // cant make it to work... 
    // code that depends on 'result' 
}); 

должно быть что-то вроде

function other_func(result) { 
    alert(result+' it works'); 
    // code that depends on 'result' 
}; 

Но, как было показано в статье, что вы связаны - это плохой путь.

Вы бы лучше разместить код, который зависит от result в успех обратного вызова или как то

function foo() { 
    var customerid = $("#edit-field-order-customer-und").val(); 
    return $.ajax({ 
      type: 'GET', 
      url: '/ops', 
      data: {'customerid': customerid}, 
    }); 

}.done(function(response) { 
    alert(response.borispol+' it works'); 
    //code that depends from result (response.borispol) or anything else 
}); 

Но! Обратите внимание, что код в done выполняется асинхронно!

0

Затратив на @ комментарий Раджа

Ajax является асинхронной. Значение к тому времени, когда ваша функция внизу работает, вы еще не закончили делать вызов. Импортируйте или вызовите ваш «код, который требует результата» в функцию успеха.

$("#edit-field-order-borispol-und").change(function() { 
    $.ajax({ 
     type: 'GET', 
     url: '/ops', 
     data: { 
      'customerid': $(this).val() 
     }, 
     success: function (response) { 
      var result = response.borispol; 
      alert(result + ' it works'); // cant make it to work.. 
      // insert code that depends on 'result' 
      // either by copy/paste 
      // or calling it: 
      codeThatNeedsResult(result); 
     } 
    }); 
}); 

Вы также можете проверить $ .ajax документацию и думать об использовании deferreds.

Смежные вопросы