[英]load specific div content using ajax
I am using $.ajax to load the page content.我正在使用 $.ajax 加载页面内容。 In response I am getting whole html document as a string but I want to get the only particular div content from the response by using id of the div.作为响应,我将整个 html 文档作为字符串获取,但我想通过使用 div 的 id 从响应中获取唯一特定的 div 内容。 I can't change the response and I can't use $.load method.我无法更改响应,也无法使用 $.load 方法。 Thanks in advance.提前致谢。
$.ajax({
url: ajax_url,
type: "GET",
dataType: "html"
}).done(function(data) {
}).fail(function(jqXHR, textStatus, errorThrown) {
});
In your .done()
method: 在您的.done()
方法中:
.done(function(data) {
$('#target').html($(data).find('#specificDivId'))
})
You can traverse the HTML returned from the request in the same manner you would the DOM of the current page. 您可以以与当前页面DOM相同的方式遍历从请求返回的HTML。 Try this: 尝试这个:
$.ajax({
url: ajax_url,
type: "GET",
dataType: "html"
}).done(function(html) {
var $divToFind = $(html).find('#myDiv');
$divToFind.appendTo('#targetElement');
}).fail(function(jqXHR, textStatus, errorThrown) {
// handle the error...
});
Alternatively, you could use the load()
method which has this functionality built in: 另外,您可以使用具有内置此功能的load()
方法:
$('#targetElement').load(ajax_url + ' #myDiv');
You can use DOM parser. 您可以使用DOM解析器。
$.ajax().success(function(data) {
var parser = new DOMParser();
var doc = parser.parseFromString(data, "application/xml");
// doc is a DOM now
});
More information: 更多信息:
https://developer.mozilla.org/es/docs/Web/API/DOMParser https://developer.mozilla.org/es/docs/Web/API/DOMParser
As AJAX returns a plain text, you can transform it to jQuery DOM element, modify it and append (or replace HTML) to your HTML. 当AJAX返回纯文本时,您可以将其转换为jQuery DOM元素,对其进行修改并将其追加(或替换HTML)到HTML中。
For example, this way: 例如,这样:
$.ajax({
url: ajax_url,
type : "GET",
dataType : "html"
}).done(function(data) {
var obj = $(data);
$("#yourdiv").html(obj.find(".something").html());
}).fail(function(jqXHR, textStatus, errorThrown) {
});
I have used .find(".something")
because I do not know the format of received message. 我使用了.find(".something")
因为我不知道接收到的消息的格式。 You can use any jQuery methods. 您可以使用任何jQuery方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.