看看我的代码:
function dialogTexts() {
var langText = $.ajax({
type: 'GET',
url: '/main/getdialogtexts',
dataType: 'json'
});
langText.done(function(data) {
//data contains a array returned correctly from php
//The data.delete is returned correctly from php. data.delete contains a string
return data.delete;
});
langText.fail(function(ts) {
alert(ts.responseText);
});
}
为什么变量lang
在调用上述函数时会获得未定义?
var lang = dialogTexts();
答案 0 :(得分:1)
您无法从异步ajax调用返回值。您只能从回调中获取其值。除非您使用不推荐的async:false
,因为它会在请求待处理期间冻结UI。
请参阅How do I return the response from an asynchronous call?
function dialogTexts(callback) {
var langText = $.ajax({
type: 'GET',
url: '/main/getdialogtexts',
dataType: 'json'
});
langText.done(function(data) {
//data contains a array returned correctly from php
callback(data.delete)
//The data.delete is returned correctly from php. data.delete contains a string
return data.delete;
});
langText.fail(function(ts) {
callback(false);
});
}
dialogText(function(text) {
alert(text);
})