最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding html and plain text inside div with jQuery - Stack Overflow

programmeradmin7浏览0评论

I'm recieving a string (it may be either plain text or HTML text) from server, and I need to insert it into a div after that.

I can use $div.text(textFromServer) if I know that textFromServer is plain text.

If I know that textFromServer is html I can do something like $(textFromServer).appendTo($div).

The problem is that I don't know for sure whether textFromServer is plain or HTML.

So here's the question: is there a elegant and simple solution for my problem? Or do I have to analyse textFromServer?

I'm recieving a string (it may be either plain text or HTML text) from server, and I need to insert it into a div after that.

I can use $div.text(textFromServer) if I know that textFromServer is plain text.

If I know that textFromServer is html I can do something like $(textFromServer).appendTo($div).

The problem is that I don't know for sure whether textFromServer is plain or HTML.

So here's the question: is there a elegant and simple solution for my problem? Or do I have to analyse textFromServer?

Share Improve this question edited Dec 19, 2012 at 10:21 VisioN 145k34 gold badges287 silver badges289 bronze badges asked Dec 19, 2012 at 9:24 Eugeny89Eugeny89 3,75110 gold badges55 silver badges105 bronze badges 3
  • Cant you just assume that the text is html and then do $div.html(textFromServer)? Even if it is plain text, it will get added fine. – Ravi Y Commented Dec 19, 2012 at 9:26
  • Just append is OK, I think? – nhahtdh Commented Dec 19, 2012 at 9:26
  • Check content-type of response ing from server, for 'text/plain' or 'text/html', based on that you can use .html() or .text() – Ranganadh Paramkusam Commented Dec 19, 2012 at 9:30
Add a ment  | 

3 Answers 3

Reset to default 7

Simply use html():

$div.html(textFromServer);

You're describing jquery.html().
$div.html(textFromServer) should do the trick.

If there in no particular reason for knowing about data type (text / html) then you can directly assign the text / html to your div using [html()][1] function like

$div.html(textFromServer)

If you are interested in knowing the type of data text / html then you can store the type of your data (text, html) in hidden field on server and access that in javascript / jQuery.

发布评论

评论列表(0)

  1. 暂无评论