javascript - 拆分 AJAX POST 变量

标签 javascript php jquery ajax post

我编写了一个脚本来在单击复选框 时发布AJAX 变量。当选择多个 checkboxes 时,变量存储在一个数组中并由 pipe 分隔。我需要将每个变量单独传递到我的 php 函数中,以便我可以运行单独的查询。

我的 JavaScript

$(document).on("change", ".tbl_list", function () {
    var tbls = new Array();
    $("input:checkbox[name='tbl[]']:checked").each(function () {
        tbls.push($(this).val());
    });
    var tbl = tbls.join('|');
    var db = window.sessionStorage.getItem("db");
    alert(db);
    $.ajax({
        type: "POST",
        url: "ajax2.php",
        data: {
            tbl: tbl,
            db: db
        },
        success: function (html) {
            console.log(html);
            $("#tblField").html(html).show();
        }
    });
});

选中多个表时的输出

tbl:db|event

我的 PHP 函数

function tblProperties() {
    if (isset ( $_POST ['tbl'] )) {
        $tbl = $_POST ['tbl'];
        $db = $_POST ['db'];
        $link = mysqli_connect ( 'localhost', 'root', '', $db );
        $qry = "DESCRIBE $tbl";
        $result = mysqli_query ( $link, $qry );

我知道我需要以某种方式存储这些变量,然后为每个变量执行一个 以生成单独的查询,但我不确定该怎么做。

最佳答案

这样做:

function tblProperties() {
    if (isset ( $_POST ['tbl'] )) {
        $db = $_POST ['db'];
        $tables = explode('|', $_POST ['tbl']); // explode your variable
        $link = mysqli_connect ( 'localhost', 'root', '', $db );

        foreach($tables as $table) // foreach through it
        {
            $result = mysqli_query ( $link, "DESCRIBE $table" ); // do your query
            while($row = mysqli_fetch_array($result))
            {
                // your code here 
            }
        }
}

关于javascript - 拆分 AJAX POST 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29341069/

相关文章:

javascript - 如何在单击侧边栏图像时将图像从侧边栏交换到中间 div?

PHP 向 Node/Socket.IO 服务器发送消息

javascript - 在链接按钮的顶部显示工具提示

javascript - 如何用 html 捕获和替换 token 中的项目

jquery - 在表中使用两个函数

javascript - JS验证多个同名输入字段

javascript - Android 在触摸选择时获取选定的文本

javascript - 使用链接调用将文件插入 div 的 javascript 函数

php/mysql 数组或带有某些值的查询

php - 如何在 ubuntu 12.04 中更改 mysql 数据目录