我有一个ajax函数,其响应是一个html表.我需要将其转换为数组.
我的回答如下:
<table>
<tr>
<td>4362</td>
<td>Education</td>
</tr>
<tr>
<td>4373</td>
<td>Education world</td>
</tr>
</table>
我需要将其更改为以下数组.
[['4362','Education'],['4373','Education world']]
我已经完成了以下ajax代码,但没有给我确切的形式.
success:function(hasil) {
var table_response = $.parseHTML($(hasil).filter('table').html());
console.log($(table_response).each(function(index, tr) {
$('td', tr).map(function(index, td) {
return $(td).text()
})
}));
}
console.log($('td', table_response).map(function(_, el) {
return $(el).html()
}));
解决方法:
(function (){
var response = `<table><tr><td>4362</td><td>Education</td></tr>
<tr><td>4373</td><td>Education world</td>
</tr>
</table>`;
var arr = [];
$(response).find('tr').each(function(index){
var row = arr[index] = [];
$(this).find('td').each(function(i){
row[i] = $(this).text();
})
})
console.log(arr);
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>