Добавить Jquery Ajax & quot; data & quot; как отдельные значения в таблице

У меня есть таблица в качестве следующей таблицы данных:

            <button id="addRow">Add New Row</button><br>
<table class="table table-striped table-bordered table-hover "  id="example" cellSpacing=0 width="100%">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tr style="text-align: center;">
<td>hola</td>
<td>ciao</td>
<td>bonjour</td>
<td>yo</td>
<td>salut</td>
</tr>
</table>

Я хотел бы добавить элементы, используя сценарий JavaScript, как показано ниже:

<script type="text/javascript">
$(document).ready(function () {
debugger;
var t = $('#example').DataTable({ "searching": true, "paging": true });
var counter = 1;
$('#addRow').on('click', function ciicici() {

var now = new Date();
var now = now.toMysqlFormat();
var tii = new Date();
tii.setSeconds(tii.getSeconds() - 50000);
var tii = tii.toMysqlFormat();
$.post( "sqlmachine_test_ajax.php", {  timing: now,seconding: tii  })
.done(function( data ) {
t.row.add([
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
]).draw();
counter++;
// });
//setTimeout(function(){ciicici();}, 5000);
}); // Automatically add a first row of data
$('#addRow').click();
});
</script>

Они работают должным образом, единственное, что я хотел бы получить элементы для добавления через сценарий Jquery AJAX.

Допустим, у меня есть страница php, отправляющая 5 значений, которые я хотел бы добавить в каждый столбец (вместо counter1, counter2 и т. Д.) Следующим образом:

<?php
echo 'counter1, counter2, counter3, counter4, counter5';
?>

и в javascript я хотел бы просто написать:

...
.done(function( data ) {
t.row.add([
data //(instead of the counters)
]).draw();
counter++;
...

Я попробовал это, а также массивы и массивы в кодировке json, но все, что я получаю, это 5 результатов в одной и той же первой ячейке таблицы.
Итак, как я могу добавить ответ ajax php в таблицу как данные в разных ячейках таблицы?

Marko

0

Решение

Когда вы получите данные обратно от вызова, вы должны отделить с помощью .split(),

так что вы можете сделать это, когда вы получите обратный звонок

.done(function( data ) {
var splitData = data.split(", ") //Split your data with the comma and space
$.each(splitData, function(e){  //For each piece of data
//Add your rows here one by one
t.row.add([
splitData[e] //Make sure the 'e' in the function and here are the same
]).draw();
})
counter++;
});

Это свободный ответ, я постараюсь добавить больше в ближайшее время.

Изменить: Больше информации

то, что я обычно делаю, это эхо все с разделителями. Так что, в вашем случае, я бы повторил 1, 2, 3, 4, 5:A, B, C, D, E, Поэтому, когда данные вернутся, это то, что вы увидите.

В ваших данных успеха, вы бы сделали что-то вроде

var dataParts = data.split(":") //This splits your data into the 2 parts using the : separator
var dataPart1 = dataParts[0] //This will get 1, 2, 3, 4, 5
var dataPart2 = dataParts[1] //this will get A, B, C, D, E

Затем оттуда вы разделяете запятыми.

var dataPieces1 = dataPart1.split(', ');
var dataPieces2 = dataPart2.split(', ');

Затем запустите петли. (используя JavaScript for цикл обычно лучше, чем использование jQuery’s .each())

for(var i = 0; i < dataPieces1.length; i++){ //Start your for loop on the first part
//Create a row here using dataPieces1[i], this will loop and make a new
//row every time the next loop finishes
for(var j = 0; j < dataPieces2.length; j++){ //Start the second loop
//Not sure how you would want to do this, but here's some example code
//Since you're inside a row now, append your dataPieces2[j] to that row
//This will loop for every dataPieces2 and append each one as a column
//in that single row.
}
}
0

Другие решения

Других решений пока нет …