jQuery ajax调用 - 返回特定的HTML元素
答
AJAX调用不会返回DOM元素。它发送一个异步HTTP请求给服务器端脚本返回其可以是任何类型的HTML的结果,XML,JSON,....然后这个结果被传递到success
回调处理:
$.get('/script', function(result) {
// TODO: do something with the result returned by the server script
});
因此,例如,如果你的服务器端脚本返回一些HTML内容,你要提取您可以做这样的特定元素:
$.get('/script', function(result) {
// get an element with id="foo" from the returned result
var foo = $(result).find('#foo');
});
答
达林是正确的。但是,您可能正在寻找由load
(Ajax方法而不是事件处理程序)提供的功能。
诸如$('#result').load('ajax/test.html #container');
之类的东西会解析ID为container
的元素的响应HTML并将其插入到result
的HTML中。 (load)()
也接受加载完成时将调用的回调)。
$('#result').load('ajax/test.html #container,.classname',
function(){
$('#result').html(); //this should give you the DOM that matches either .classname or #container
});