Dreams
Dreams

Reputation: 8506

How to encode the url from ajax return data then append to html?

$.ajax({
  url: "get_title_list.php", //server API name
  type: 'POST',
  dataType: 'json',
  data: {id: id},
  async: true,
  cache: false,
  success: function(response) {
    if(response.length!=0)
    {
      $("#faq").html('');
      var html = '';
      $.each(response, function(index, array) {
        // fi_title:標題文字, fi_content:內容文字
        html+='<div class="content">'
          +'<table width="100%" border="0">'
            +'<tr>'
            +'<td style="width:50px;vertical-align:top;"><img src="answer_icon.jpg" style="width:20px;" /></td>'
            +'<td style="text-align:left;">'+ array['fi_content'] +'</td>'
            +'</tr>'
          +'</table>'
        +'</div>';
      });
      $("#faq").append(html); 
    }
  },
});

I will have content in "array['fi_content'] and in this content may have some string and with a url like below.

" Welcome to my website.Visit link. http://www.mypage.com "

In google debug mode, it will look like

<p>
Welcome to my website.Visit link.
<a target="_blank" href="http://www.mypage.com">http://www.mypage.com</a>
</p>

My question is how to encode the url before append to html? Can I use get url by href attribute and change it then append it with string ?

Upvotes: 2

Views: 143

Answers (2)

FelisCatus
FelisCatus

Reputation: 5334

If you want to make some changes to the href attribute, the easiest way would be parsing it as HTML and then change the DOM. Since you are using jQuery, you can also use its parsing.

var content = $(array['fi_content']); // parses HTML as jQuery object.
content.find("a").each(function (_, link) {
  var href = link.getAttribute("href"); // Do not use .href as it contains parsed absolute URL instead.
  // Do any encoding you like to href here.
  link.href = href; // Set the href back to element.
});
var processedContentHtml = content.html();
// You can now concat processedContentHtml into your string.
// Ex: +'<td style="text-align:left;">'+ processedContentHtml +'</td>'

Upvotes: 2

Finesse
Finesse

Reputation: 10801

Replace array['fi_content'] to this:

array[ 'fi_content' ].replace( /<a(\s[^>]*\s|\s)href=[\"\']([^\"\']*)[\"\']([^>]*)>/ig, function( s1, url, s2 ) {
    return '<a' + s1 + 'href="' + encode( url ) + '"' + s2 + '>';
} );

I don't have any idea what mean saying encode so I just pass url to function encode which you should implement by yourself.

Upvotes: 0

Related Questions