嵌套在AJAX输出中的jQuery AJAX函数(innerHTML)

时间:2016-06-08 04:46:59

标签: javascript php jquery mysql ajax

我使用jQuery Ajax(innerHTML)生成MySQL数据库中的记录列表。我想在每个记录旁边放一个DELETE按钮。

按下DELETE按钮后,记录将从数据库中删除,并从显示的列表中消失。是否可以这样做 - 在innerHTML输出中嵌套另一个jQuery Ajax函数?

请注意,我使用的DELETE函数可以很好地处理标准的PHP / HTML输出。

在主要的php文件(test1.php)中我有表单来选择一个时间范围,一旦表单被提交,函数bellow就会在同一个文件中生成我的输出:

<div id="display_taxation_data"></div>

负责生成列表的代码:

function showDataLabour(str) {
if (str == "") {
    document.getElementById("display_taxation_data").innerHTML = "<h3>No results. Please select taxation period.</h3><hr>";
    return;
} else {
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("display_taxation_data").innerHTML = xmlhttp.responseText;
        }
    };
    xmlhttp.open("GET","accounting_get_period_data_labour.php?period="+str,true);
    xmlhttp.send();
    }
}

accounting_get_period_data_labour.php的代码(根据先前选择的时间范围生成的记录集。)

echo "<tr id='record-$id'>";
echo "<td width='40'><a href='accounting_expenses_delete.php?delete=$id' class='delete'><i class='fa fa-times fa-2x' aria-hidden='true' title='Delete'></i></a></td>";
echo '</tr>';

按下按钮DELETE后,删除我要触发的功能:

$(function() {
$('a.delete').click(function(e) {
    e.preventDefault();
    var parent = $(this).parent("td").parent("tr");
    console.log('idno : ' + parent);
    $.ajax({
        type: 'post',
        url: 'accounting_expenses_delete.php',
        data: 'delete=' + parent.attr('id').replace('record-',''),
        beforeSend: function() {
            parent.animate({'backgroundColor':'#fb6c6c'},100);
        },
        success: function() {
            parent.fadeOut(100,function() {
                parent.remove();
            });
        }
    });
});
});

最后是accounting_expenses_delete.php的短代码

<?
include "connectdb_mysqli.php"; 
$testdel = $_POST['delete'];
$result = $mysqli->query("DELETE FROM `test` WHERE id='$testdel'"); 
 ?>

如果您需要更多信息,请与我们联系。

期待您就如何实现DELETE行动提出建议或解决方案。谢谢

5 个答案:

答案 0 :(得分:1)

我们可以为每个要删除的链接添加data-id标记:

echo '<td width="40">
          <a href="#" data-id="'.$id.'" class="delete"><i class="fa fa-times fa-2x" aria-hidden="true" title="Delete"></i></a>
      </td>';

单击此按钮后,它将运行Ajax请求:

$(document).on('click', '.delete', function(e) {

    e.preventDefault();

    var elem = $(this),
        id = elem.attr('data-id'); /* GET THE ID NO. OF THE CLICKED DELETE LINK */

    $.ajax({ /* AJAX REQUEST */
        type: 'post',
        url: 'accounting_expenses_delete.php',
        data: {'delete-id': id},
        success: function() {
            elem.closest('tr').hide(200);
        }
    });
    return false;
});

然后是accounting_expenses_delete.php

include('connectdb_mysqli.php');

$stmt = $mysqli->prepare("DELETE FROM test WHERE id = ?");
$stmt->bind_param("i", $_POST["delete-id"]);
$stmt->execute();
$stmt->close();

我使用prepared statement执行上面的DELETE查询。

注意:

jQuery是一个javascript库,我提供的脚本是一个jQuery,所以这意味着你必须首先在脚本之前包含jQuery库。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
<script>
    /* YOUR JQUERY SCRIPT HERE */
</script>

答案 1 :(得分:0)

您是否将值从PHP传递给JavaScript?如果是这样,你可能会对eval()有一些好处,它可以执行存储在字符串中的代码块。

答案 2 :(得分:0)

您使用原始Javascript进行首次AJAX调用以获取商家信息。突然间,您正在更改为JQuery以进行删除。为什么不在Pure Javascript或JQuery中同时执行这两项操作?我认为JQuery更容易一些。下面是一个基于JQuery的解决方案,用于获取和删除数据:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script type="text/javascript">
        (function ($) {
            $(document).ready(function (e) {

                function showDataLabour(str) {
                    var taxDataBlock   = $("#display_taxation_data");

                    if(str == ""){
                        taxDataBlock.html("<h3>No results. Please select taxation period.</h3><hr>");
                    }else{
                        $.ajax({
                            type    : 'GET',
                            url     : 'accounting_get_period_data_labour.php?period=' + str,
                            success : function(data) {
                                if(data){
                                    taxDataBlock.html(data);
                                    var generatedData   = $(data);
                                    var deleteBtn       = generatedData.find("a.delete");
                                    // SINCE THE LISTINGS ARE GENERATED HERE,
                                    // TARGET < a class='delete'> ELEMENT(S) WITHIN THE GENERATED CONTENT
                                    // AND PASS IT AS AN ARGUMENT TO THE DELETE FUNCTION...
                                    deleteViaAjax(deleteBtn);
                                }
                            }
                        });
                    }
                }

                function deleteViaAjax(deleteBtn){
                    deleteBtn.click(function(e) {
                        e.preventDefault();
                        var parent = $(this).parent("td").parent("tr");
                        console.log('idno : ' + parent);

                        $.ajax({
                            type: 'post',
                            url : 'accounting_expenses_delete.php',
                            data: {'delete': parent.attr('id').replace('record-','')},
                            beforeSend: function() {
                                parent.animate({'backgroundColor':'#fb6c6c'},100);
                            },
                            success: function() {
                                parent.fadeOut(100,function() {
                                    parent.remove();
                                });
                            }
                        });
                    });
                }
            });
        })(jQuery);

    </script>

答案 3 :(得分:0)

你的 delete()函数使用jQuery进行ajax调用。为什么 showDataLabour()函数使用原生XMLHttpRequest?使用jQuery也更好: - )

你不能使用:

$(function() {
    $('a.delete').click(function(e) {
        // your code for delete action
    });
});

单击事件绑定到删除按钮,因为在完全加载页面时该按钮不存在。它将存在 AFTER 由showDataLabour()函数完成的ajax调用已经完成。

在这种情况下,您可以使用委派活动。试试这个:

$(function() {
    $('body').on('click', 'a.delete', function(e) {
        // your code for delete action
    });
});

阅读http://api.jquery.com/on/了解更多信息。

答案 4 :(得分:0)

2016-06-08 15:19:01,635 (SinkRunner-PollingRunner-DefaultSinkProcessor) [WARN - org.apache.flume.sink.hdfs.HDFSEventSink.process(HDFSEventSink.java:455)] HDFS IO error
org.apache.hadoop.ipc.RemoteException: Server IPC version 9 cannot communicate with client version 4
    at org.apache.hadoop.ipc.Client.call(Client.java:1070)
    at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:225)
    at com.sun.proxy.$Proxy5.getProtocolVersion(Unknown Source)
    at org.apache.hadoop.ipc.RPC.getProxy(RPC.java:396)
    at org.apache.hadoop.ipc.RPC.getProxy(RPC.java:379)
    at org.apache.hadoop.hdfs.DFSClient.createRPCNamenode(DFSClient.java:119)
    at org.apache.hadoop.hdfs.DFSClient.<init>(DFSClient.java:238)
    at org.apache.hadoop.hdfs.DFSClient.<init>(DFSClient.java:203)
    at org.apache.hadoop.hdfs.DistributedFileSystem.initialize(DistributedFileSystem.java:89)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:1386)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:66)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:1404)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:254)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:187)
    at org.apache.flume.sink.hdfs.BucketWriter$1.call(BucketWriter.java:243)
    at org.apache.flume.sink.hdfs.BucketWriter$1.call(BucketWriter.java:235)
    at org.apache.flume.sink.hdfs.BucketWriter$9$1.run(BucketWriter.java:679)
    at org.apache.flume.auth.SimpleAuthenticator.execute(SimpleAuthenticator.java:50)
    at org.apache.flume.sink.hdfs.BucketWriter$9.call(BucketWriter.java:676)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)