【发布时间】:2012-11-24 15:22:50
【问题描述】:
小提琴:http://jsfiddle.net/gpTpK/
我遇到的问题是执行 $.ajax 时标题变量没有更新/更改,我知道 ajax 调用正在工作,因为我尝试替换该行
title = $(xml).find("title").text();
与
console.log($(xml).find("title").text());
果然它确实返回了标题,但是当使用原始行时,变量标题不会改变
我已经尝试过,它确实可以将 ajax 调用放在外部 (function($){})(jQuery);
(function($) {
$.fn.getPost = function(options) {
var $this = $(this);
var defaults = {
method: "html",
blogID: "",
postID: "",
done: null
};
var options = $.extend(defaults, options);
var title;
$.ajax({
type: "GET",
url: "http://www.blogger.com/feeds/724793682641096478/posts/default/3551136550258768001",
dataType: "xml",
dataType: 'jsonp',
success: function(xml) {
title = $(xml).find("title").text();
}
});
return $this.each(function() {
if (options.done) {
options.done.call(undefined, title);
}
});
};
})(jQuery);
我已经尝试过以下方法,我还尝试将 ajax 包装在一个函数中,例如 getTitle(){ajax code here with return title;}
(function($) {
$.fn.getPost = function(options) {
var $this = $(this);
var defaults = {
method: "html",
blogID: "",
postID: "",
done: null
};
var options = $.extend(defaults, options);
var title;
getAjax();
return $this.each(function() {
if (options.done) {
options.done.call(undefined, title);
}
});
function getAjax() {
$.ajax({
type: "GET",
url: "http://www.blogger.com/feeds/724793682641096478/posts/default/3551136550258768001",
dataType: "xml",
dataType: 'jsonp',
async: false,
success: function(xml) {
title = $(xml).find("title").text();
}
});
}
};
})(jQuery);
【问题讨论】:
-
返回几乎总是发生在 AJAX 请求调用提供给成功的函数之前。
-
@nhahtdh 不是几乎 ... 总是
标签: ajax jquery jquery-plugins