我的问题是如何获取一个页面的 HTML 并将其存储在一个对象中,稍后我可以使用 jQuery 方法搜索该对象,以按 id、名称、类等获取元素。
这是我到目前为止所拥有的:
$(document).ready(function(){
$('#button').click(function() {
var page = $.ajax({
type: 'GET',
url: 'Grabber.php',
data: {url:$('#url')},
dataType: "HTML",
success: function(data){
alert(data); //this alert displays the correct information
}
}).responseText;
alert(page); //this alert displays nothing
});
});
我怎样才能让“页面”变量起作用?更好的是,我如何存储它,以便我可以像访问 HTML 文档一样访问它。到目前为止我唯一的想法就是作为 DOM 文档。
最佳答案
$(document).ready(function(){
var page;
$('#button').click(function() {
$.ajax({
type: 'GET',
url: 'Grabber.php',
data: {url:$('#url')},
dataType: "HTML",
success: function(data){
populate(data);
}
});
function populate(a) {
page = a;
alert(page)
alert($(page).find('span').text())
}
});
});
检查documentation ,$.ajax
返回 XMLHttpRequest
,而 success 方法返回 data、textStatus、XMLHttpRequest
。您在这里需要的是数据
要访问它,您可以执行以下操作:
$(page).find('span').text()
关于jquery - 如何将 .ajax() responseText 设置为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4697488/