gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:42:02 26 4
gpt4 key购买 nike

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

我将在 "array['fi_content'] 中包含内容,并且在该内容中可能包含一些字符串和如下所示的 url。

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

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

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

我的问题是如何在附加到 html 之前对 url 进行编码?我可以使用通过 href 属性获取 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>'

关于javascript - 如何从 ajax 返回数据编码 url 然后附加到 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32437894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com