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

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

本文关键字:数据 返回 然后 追加 html ajax 何编码 编码 url      更新时间:2023-09-26
$.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="answerswer_icon.jpg" style="width:20px;" /></td>'
            +'<td style="text-align:left;">'+ array['fi_content'] +'</td>'
            +'</tr>'
          +'</table>'
        +'</div>';
      });
      $("#faq").append(html); 
    }
  },
});

我将有内容在"array['fi_content']和在这个内容可能有一些字符串和url如下。

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

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

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

我的问题是如何在附加到html之前编码url ?

如果您想对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>'

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,你应该自己实现。