2015-09-07 43 views
2
$.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); 
    } 
    }, 
}); 

我將在內容「數組[‘fi_content’]在這個內容可能有一些字符串和一個網址,如下所示。如何從ajax返回數據編碼url然後附加到html?

」歡迎來到我的website.Visit鏈接。 http://www.mypage.com

在谷歌調試模式下,它看起來像

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

我的問題是如何編碼的URL之前追加到HTML嗎? 我可以使用Get URL通過href屬性,並改變它,然後將其追加?用繩子

+0

是否指爲字符串中的所有網址添加鏈接? – FelisCatus

+0

不,我的意思是如何在ajax返回數據中找到一個url,然後將其編碼並再次追加。 – Dreams

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

我可以問一個問題......如果什麼有兩個或多個網址數組[「fi_content」]? – Dreams

+0

此解決方案適用於'array ['fi_content']'中的每個''標籤。所以不要擔心,一切都會好的。 – FelisCatus

+0

對不起,我沒有看到你使用.each。 – Dreams

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 + '>'; 
}); 

我沒有任何想法是什麼意思SA ying encode所以我只是通過url功能encode,你應該自己實現。

相關問題