我在自定义函数中有ajax函数,我需要调用自定义函数并从ajax函数中获取一些变量。为什么这不可能?
第一个想法:
<script>
function getValue(){
$.nette.ajax({
url: "http://example.com/request",
contentType: 'application/json',
dataType: 'json',
success: function(payload) {
console.log(payload.value); // contains RIGHT value
return payload.value;
}
});
}
var try = getValue();
console.log(try); // = undefined
</script>
第二个想法:
<script>
function getValue(){
var returning = "";
$.nette.ajax({
url: "http://example.com/request",
contentType: 'application/json',
dataType: 'json',
success: function(payload) {
returning = payload.value;
console.log(payload.value); // contains RIGHT value
}
});
console.log(returning); // = ""
}
</script>
答案 0 :(得分:2)
ajax是一个承诺。在请求成功时使用回调来执行某些操作
function getValue(callback){
$.nette.ajax({
url: "http://example.com/request",
contentType: 'application/json',
dataType: 'json',
success: function(payload) {
callback(playload);
}
});
}