I am using $.ajax to load the page content. 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. I can't change the response and I can't use $.load method. Thanks in advance.
$.ajax({
url: ajax_url,
type: "GET",
dataType: "html"
}).done(function(data) {
}).fail(function(jqXHR, textStatus, errorThrown) {
});
In your .done()
method:
.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. 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:
$('#targetElement').load(ajax_url + ' #myDiv');
You can use DOM parser.
$.ajax().success(function(data) {
var parser = new DOMParser();
var doc = parser.parseFromString(data, "application/xml");
// doc is a DOM now
});
More information:
As AJAX returns a plain text, you can transform it to jQuery DOM element, modify it and append (or replace HTML) to your 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. You can use any jQuery methods.
What you want is basically what ajax shorthand method load() using page frament is doing:
$('#divToAddContent').load(ajax_url + ' #divToGetContent');
(note the space at starting fragment selector string)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.