我对一个外部站点进行了Ajax调用,从一个特定的元素中获取一些信息,并将其作为字符串返回到我的站点上。
这是AJAX调用的代码:
$.ajax({
url: 'http://cors.io/?u=http://www.spotlight.com/6298-9058-7917',
type: 'GET',
success: function(res) {
var data = $.parseHTML(res);
$(data).find('.credit').each(function(){
$('#credits').append($(this).html());
});
}
});
这个get是外部站点上名为
.credit
的div的所有内容,返回如下:<div id="credits">
<span class="creditYear">2010</span>, <span class="creditProductionType">Television</span>, <span class="creditCharacterRole">Cop Nicola Lanza</span>, <span class="creditProductionName">“Un posto al sole”</span>, <span class="creditCompany">Grundy</span>, <span class="creditDirector">Various</span><span class="creditYear">2008</span>, <span class="creditProductionType">Television</span>, <span class="creditCharacterRole">Lawyer Moroni</span>, <span class="creditProductionName">“Il Bene e il Male”</span>, <span class="creditCompany">Italy</span>, <span class="creditDirector">Giorgio Serafini</span>
</div>
显然,在我的页面上,这看起来有点混乱,我想能够做的是把它很好地设计成一个表格。因此,对于每组结果(即年份、生产、角色、生产名称、公司、主管),表中应该有一行,如下所示:
<table>
<tr>
<td class="year"></td>
<td class="production_type"></td>
<td class="character_role"></td>
<td class="production_name"></td>
<td class="company"></td>
<td class="director"></td>
<td class="director"></td>
</tr>
</table>
…但每组结果只有一行。是否可以附加每个对应的信用(来自AJAX调用)并将其显示在我的表中?
最佳答案
可以通过将每个跨距中的数据复制到表的相关单元格来完成此操作:
在您的成功回访中:
// Set up the table however you want it to be formatted
var $tableTemplate = $('<table><tr>' +
'<td class="year"></td>' +
'<td class="production_type"></td>' +
'<td class="character_role"></td>' +
'<td class="production_name"></td>' +
'<td class="company"></td>' +
'<td class="director"></td>' +
'</tr></table>');
$(data).find('.credit').each(function(){
// Copy the data from the request to a copy of the table
var $newTable = $tableTemplate.clone();
var $creditData = $(this);
$newTable.find('.year').text($creditData.find('.creditYear').text());
$newTable.find('.production_type').text($creditData.find('.creditProductionType').text());
$newTable.find('.character_role').text($creditData.find('.creditCharacterRole').text());
$newTable.find('.production_name').text($creditData.find('.creditProductionName').text());
$newTable.find('.company').text($creditData.find('.creditCompany').text());
$newTable.find('.director').text($creditData.find('.creditDirector').text());
// And append it to your div (or whatever you want to put it in)
$('#credits').append($newTable);
}
演示:https://jsfiddle.net/p5zetyam/
关于javascript - 如何使用jQuery分别分离字符串中的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37292728/