我正在使用ajax请求从服务器检索文本字符串。 我尝试使用 .load((,但问题是它在运行我的回调函数(它只是逐个字母显示文本(之前将文本注入页面。
因此,为了缓解这种情况,我迁移到 .ajax(( 并在成功回调中使用了我的函数。这适用于逐个字母显示文本。
这是我的问题。当服务器没有更多字符串时,该站点应该将您重定向到另一个页面。这正是使用 .load(( 时发生的情况。
但是,当使用 .ajax(( 时,来自服务器的原始 HTML 被注入到当前页面中,并且没有正确呈现。
我不确定如何解决这个问题,我已经在网上搜索了很长时间了。下面是每个方法的代码。
.load(( 方法(无逐个字母回调(
$('#nextButton').click(function(){
$('#thonow').load('next.php');
});
.ajax(( 方法(逐个字母回调(
$('#nextButton').click(function(){
$.ajax({
url: 'next.php',
dataType: 'text',
success: function(result) {
$('#thonow').html("");
lbyl('#thonow',result,0,50);
}
});
});
以防万一您需要 lbyl 功能...
var lbyl = function (target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () {
lbyl(target, message, index, interval);
}, interval);
}
};
任何协助将不胜感激。
要直接回答您的问题,ajax()
相当于$('#thonow').load('next.php')
是;
jQuery.ajax('next.php', {
type: 'GET',
dataType: 'html'
}).done(function (response) {
$('#thonow').html(response);
});
请注意,load()
中有更多的逻辑,因此并非所有load()
调用都等效于此ajax()
调用,但在这种情况下,它是等效的。
但是,这实际上并不能帮助解决您的问题。因为您的lbyl
函数一次append()
一个字符的响应,所以 jQuery 将每个字符视为Text
节点*,而不是load()
将其视为的 HTML 字符串。这就是为什么您看到正在输出的 HTML 字符串,而不是正在解析的 HTML 字符串。
* append()
内部调用domManip()
,它本身调用 jQuery.buildFragment()
,如果传递的字符串看起来不像 HTML 字符串,则最终创建一个 Text 节点
您真正需要做的是检测响应是"整页刷新"还是"逐个字母的响应"。给定您的示例响应,您可以通过以下方式执行此操作:
$('#nextButton').click(function(){
$.ajax({
url: 'next.php',
dataType: 'text',
success: function(result) {
if (result.slice(0, 15) === '<!DOCTYPE html>') {
document.write(result);
document.close();
} else {
$('#thonow').html("");
lbyl('#thonow',result,0,50);
}
}
});
});
请注意,通过 AJAX 替换整个页面有点"代码气味"。我宁愿将用户重定向到新 URL,或者只替换<body>
或后代中的页面。