javascript - AJAX:将值数组发布到 php

标签 javascript php jquery ajax

我对 javascript/jquery 几乎一无所知:

我有一个 ajax 调用,它返回 html 表中格式化的条目,如下所示:

Stuff |   Other stuff  |  delete stuff
------|----------------|-------------------------
value1| from database  | delete this entry button
------|----------------|-------------------------
value2| from database  | delete this entry button

上面写着“删除内容”的列有一个按钮,可以调用删除该条目的方法。我一直在尝试做的是将支票簿添加到每行的末尾,并将一个数组发送到 php 来执行多记录删除。

这是电话:

 $('#menu-notifications').click(function() { 
                $.ajax({
                    type: 'GET',
                    url: '/admin/notifications/ajax_view_notifications/' + <?= $this->session->userdata('user_id'); ?>,
                    dataType: 'json',
                    cache: false,
                    success: function(data) {
                        $("#notifications-modal .modal-body table").find("tr:gt(0)").remove();
                        $.each(data, function(i, obj) {
                            $('#notifications-modal .modal-body table tr:last').after(
                                                    '<tr><td>' + htmlDecode(obj.message) + '</td>' + 
                                                    '<td>' + obj.created_by + '</td>' + 
                                                    '<td>' + obj.created_dt + '</td>' + 
                                                    '<td><div class="btn-group">' + 
                                                    '<a href="/admin/notifications/ajax_delete_notification/' + obj.id + '" class="btn btn-mini delete-notification" id="delete-notification" data-dismiss="modal"><i class="icon-remove"></i></a>' +
                                                    // here should be a checkbox to mark for deletion
                                                    '</div></td></tr>');
                        });
                    }
                });

我已成功添加复选框,但每次尝试都会出现<?=form_open();?>或打开另一个表单导致页面根本无法加载(控制台中没有任何内容)。

总结一下:我试图在每行的末尾附加一个复选框,我可以标记这个复选框,并将每个标记的复选框发送到一个方法。

最佳答案

您需要使用 HTML array 创建每个复选框,它的值将是元素 id,那么您需要一个操作(例如“删除全部”按钮),通过 Ajax 将数据发送到 PHP(无需表单):

$('#menu-notifications').click(function() {
    // Simpler: use getJSON
    $.getJSON('/admin/notifications/ajax_view_notifications/' + <?= $this->session->userdata('user_id'); ?>)
    // Clearner: use promises :)
    .done(function(data) {
        $("#notifications-modal .modal-body table").find("tr:gt(0)").remove();
        $.each(data, function(i, obj) {
            // Create a row
            var row = $('<tr>');
            // Crete cells
            var cells =
                '<td>' + htmlDecode(obj.message) + '</td>' +
                '<td>' + obj.created_by + '</td>' +
                '<td>' + obj.created_dt + '</td>' +
                // We use this identified cell to create our delete functionality
                '<td class="delete-row"></td>';
            // Fill the row
            row.append(cells);
            // Create the delete button
            var deleteButton = $('<a>', {
                 'href':        '/admin/notifications/ajax_delete_notification/' + obj.id
                ,'class':       'btn btn-mini delete-notification'
                // We can't have duplicate ids, so no ids here
                // ,id:         'delete-notification'
                ,'data-dismiss':'modal'
                ,'html':        '<i class="icon-remove"></i>'
            });
            // Crete the checkbox
            var checkbox = $('input', {
                 'type':        'checkbox'
                // We use an HTML array
                ,'name':        'rowsToDelete[]'
                ,'value':       obj.id
            });
            // Append the button and the checkbox to the row
            // I ignore the .btn-group on purpose
            row.find('.delete-row')
                .append(deleteButton)
                .append(checkbox);
            // We add the row to the DOM
            $('#notifications-modal .modal-body table tr:last').append(row);
        });
    });

});

// To delete in group we use a different call, let's say, a 'Delete All' button
$('#delete-all').click(function() {
    // We serialize the info of all the buttons
    // Find all checkbox under the .delete-row class and serialize it
    data = $('.delete-row').find(':checkbox').serialize();
    // Send the data to PHP
    $.post('/admin/notifications/ajax_delete_notification/delete_a_bunch', data)
    // PHP would receive $_POST['rowsToDelete'] = [1, 2, 4, 20]
    .done(function(data) {
        alert('All selected rows were deleted');
    })
    .fail(function() {
        alert('No rows deleted :/');
    });
});
<小时/>

测试片段

// To delete in group we use a different call, let's say, a 'Delete All' button
$('#delete-all').click(function() {
    // We serialize the info of all the buttons
    // Find all checkbox under the .delete-row class and serialize it
    data = $('.delete-row').find(':checkbox').serialize();
  
    // Alert the data (test only)
    $("#r").text(data.replace(/deleteRow/g, '$_POST[deleteRow]').replace(/%5B%5D/g, '[]').replace(/\&/g, ";\n") + ';');
  
    /*
    // Send the data to PHP
    $.post('/admin/notifications/ajax_delete_notification/delete_a_bunch', data)
    // PHP would receive $_POST['rowsToDelete'] = [1, 2, 4, 20]
    .done(function(data) {
        alert('All selected rows were deleted');
    })
    .fail(function() {
        alert('No rows deleted :/');
    });
    */
});
table {
  width: 100%;
}
th, td {
  border-bottom: 1px solid #ddd;
  text-align: left;
}
#r {
  display: block;
  border-top: 1px solid #ddd;
  padding: 10px 0;
  margin-top: 10px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table>
	<thead>
		<tr>
			<th>Dummy header</th>
			<th>Dummy header</th>
			<th>Dummy header</th>
			<th>Check to delete</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>Dummy Text</td>
			<td>Dummy Text</td>
			<td>Dummy Text</td>
			<td class="delete-row">
				<input type="checkbox" name="deleteRow[]" value="2">
			</td>
		</tr>
		<tr>
			<td>Dummy Text</td>
			<td>Dummy Text</td>
			<td>Dummy Text</td>
			<td class="delete-row">
				<input type="checkbox" name="deleteRow[]" value="3">
			</td>
		</tr>
		<tr>
			<td>Dummy Text</td>
			<td>Dummy Text</td>
			<td>Dummy Text</td>
			<td class="delete-row">
				<input type="checkbox" name="deleteRow[]" value="6">
			</td>
		</tr>
		<tr>
			<td>Dummy Text</td>
			<td>Dummy Text</td>
			<td>Dummy Text</td>
			<td class="delete-row">
				<input type="checkbox" name="deleteRow[]" checked value="10">
			</td>
		</tr>
	</tbody>
</table>
<hr>
<button id="delete-all">Delete all elements</button>
<pre id="r"></pre>

关于javascript - AJAX:将值数组发布到 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26143582/

相关文章:

javascript - jquery 验证 1.8.1 "jQuery"是未定义的错误 IE8

php - 隐藏字段数据未插入 Mysql

PHP - html 文本的 substr

javascript - 将变量添加到组合后,将另一个元素添加到 jQuery 选择器

服务器响应中的 jQuery .find()

php - 使用 PHP 和 jQuery 进行实时聊天。在哪里存储信息? mysql还是文件?

javascript - 一周中有多少人注册

javascript - 遍历对象时遇到问题

javascript - 从 .js 文件中提取动态菜单并在 html 中显示

PHP 数组,当值更改为带有开始和结束键的新数组时分割数组