I'm using jQueryUI autocomplete to pull results from a SQL database. I use the substring
method to limit results' descriptions to 350 characters. But it seems that I can't use .text()
alongside with substring to remove all the html tags from the descriptions. When I type in a search term, the console returns
TypeError: item.description.text is not a function
Can someone tell me what should be used to remove html tags from descriptions?
$(function() {
$( "#Search" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "get.php",
dataType:"json",
data:{q:request.term},
success: function( data ) {
response($.map( data.products, function( item ) { return {
label:item.name,
category:item.category,
description:item.description.text().substring(0,350).split(" ").slice(0, -1).join(" ")
//.text() doesn't work.
}
Assigning the Data:
}).data("ui-autocomplete")._renderItem = function(ul, item) {
var inner_html = '..........<p>'+ item.description +'...</div></div></a>';
The problem is that .text()
is a method of jQuery objects (which contain nodes), and .textContent
is a property of nodes. Instead, it seems that item.description
is a string.
Then, you could create a DOM element with the string as its html, and then use .textContent
or .text()
. But that is a vulnerable practice:
$('<img src="//" onerror=alert("hacked!") />');
The safe way is:
function stripHTML(html) {
var sandbox = document.implementation.createHTMLDocument().body;
sandbox.innerHTML = html;
return sandbox.textContent;
}
/* ... */
description: stripHTML(item.description).substring(0,350);
/* ... */
Note document.implementation.createHTMLDocument
doesn't work on old browsers.
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.