如何从ajax返回数据编码url然后追加到html?

时间:2015-09-07 11:44:19

标签: javascript jquery ajax

$.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); 
    }
  },
});

我会在&#34;数组[&#39; fi_content&#39;]中包含内容,并且此内容中可能包含一些字符串和下面的网址。

&#34;欢迎来到我的网站。访问链接。 http://www.mypage.com&#34;

在谷歌调试模式下,它看起来像

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

我的问题是如何在追加到HTML之前对网址进行编码? 我可以通过href属性使用get url并更改它然后用字符串附加吗?

2 个答案:

答案 0 :(得分:2)

如果要对href属性进行一些更改,最简单的方法是将其解析为HTML,然后更改DOM。由于您使用的是jQuery,因此您也可以使用它的解析。

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>'

答案 1 :(得分:0)

array['fi_content']替换为:

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

我不知道说encode是什么意思所以我只是将url传递给你应该自己实现的encode函数。