I have a jquery $.get() call in my app that requests an entire web page. In the callback function, I access a div in the returned page, get its data and show it on my page.
The problem is that the text I get from the div does not preserve the source formatting. If the div in the requested page had say 开发者_开发百科an ordered list, then when i get that text and display on my page, it shows up as a paragraph with items inline instead of being shown as a list.
I do not know whether the problem is how $.get() is getting the data or in my displaying of the data.
//get the page
$.get($(this).attr('href'), function(data){
callbackFunc(data,myLink);
},
"html");
function callbackFunc(responseText, customData){
//response has bg color of #DFDFDF
var td = $("td[bgcolor='#DFDFDF']", responseText);
//text to show is in div of that td
var forumText = $('div', td).text();
//append new row with request data below the current row in my table
var currentRow = $(customData).parent('td').parent('tr');
var toAppend = "<tr><td class='myTd' colspan='3'>" + forumText + "</td></tr>";
$(currentRow).after(toAppend);
}
The response data shows up like ABC in the new row I add to my div while the source page div had
A B CI should add that this script is part of an extension for Google Chrome so that is my only browser that I have tested on
Try using .html instead of .text:
var forumText = $('div', td).html();
I stumbled across this thread because I needed to preserve the formatting too. However using .html() instead of .text() is not an option because someone could inject a JavaScript attack this way. I found the solution I was looking for on this stackoverflow thread.
So for example, change the following lines in your code to preserve white space while still using .text() using the white-space CSS style:
var toAppend = '<tr><td class="myTd" colspan="3" style="white-space: pre-line;">'
+ forumText + "</td></tr>";
精彩评论