首先,我使用jQuery的$ .ajax函数获取HTML。为什么没有字符串传递到函数 - jQuery
在成功函数中,我提醒它(这个工作正常,并按预期显示一个HTML字符串);
然后我把它作为变量传递给另一个函数processHTML。但它不工作,并说该变量为空。我用警报证实了这一点。
var my = my || {};
jQuery(function ($) {
my.html = {
getHTML: function(url) {
$.ajax({
url: url,
dataType: "html",
success: function(myHTML) {
alert(myHTML); // shows string, as expected
my.html.processHTML(myHTML); //returns null
}
});
},
processHTML: function (myHTML) {
alert(myHTML);
// do stuff and return myHTML
}
} // end of my.html object
}); // end of jQuery wrapper function
为什么不是从成功回调传递到processHTML函数的字符串?如果我将成功回调中的myHTML替换为实际字符串(<div>test</div>
),它将成功传递到函数中。
更新:下面是实际的代码,如要求。点击链接onclick="hey.mydoc.ajax2({source: 'http://www.mysite.com/mypage'})"
进行调用。这也在JSFiddle上,但当点击链接时,我得到ReferenceError: Can't find variable: hey
,这不会发生在我的网站上。
var hey = hey || {};
jQuery(function ($) {
hey.mydoc = {
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
getHTML: function (source) {
$.ajax({
url: source,
dataType: "html",
beforeSend: function(){
},
success: function(myHTML) {
alert('myHTML is '+myHTML);
hey.mydoc.processHTML(myHTML);
} // end of success function
});
}, // end of method
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
processHTML: function (myHTML) {
alert ('processHTML - ' + myHTML);
myHTML = $(myHTML);
myHTML.find('script').remove();
// and a bunch of other DOM manipulations...
var content = "<!DOCTYPE html><html>" + myHTML.html() + "</html>";
return content;
}, // end of method
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
ajax2: function (options){
$.ajax({
url: options.content,
dataType: "html",
success: function(myHTML) {
alert('myHTML is '+myHTML); // myHTML is string of html, as expected
var newHTML = hey.mydoc.processHTML(myHTML); // myHTML not getting passed in
alert(newHTML);
} // end of success function
});
} // end of method
} // end of hey.mydoc namespace
}); //end of jQuery wrapper
请张贴给您麻烦的实际代码。这看起来像是一个削减我的例子。 – 2012-01-31 20:34:00
这是你的实际代码? 'var getHTML:function(url)'将立即失败,并带有'Unexpected token:'错误。 – ShankarSangoli 2012-01-31 20:34:35
这是您确切的JavaScript代码或您复制粘贴的部分吗?语法看起来很奇怪,因为它使用':'和'='来定义函数。你在控制台中是否收到错误信息? – 2012-01-31 20:35:07