【问题标题】:Splitting AJAX POST variables拆分 AJAX POST 变量
【发布时间】:2015-06-03 03:57:40
【问题描述】:

我编写了一个脚本来发布AJAX 变量,只要单击checkbox。 When multiple checkboxes are selected the variables are stored in an array and seperated by a 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 );

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

【问题讨论】:

标签: javascript php jquery ajax post


【解决方案1】:

这样做:

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 
            }
        }
}

【讨论】:

  • 嗨,大卫,感谢您的回复。我在函数的后面有一个问题我有这个代码while ( $row = mysqli_fetch_array ( $result ) ) {这是填充我的表格的内容,我将如何修改它,因为目前我在使用$results时没有得到任何结果。
  • $results 现在是一个数组。因此,使用foreach($results as $result) { while($row = mysqli_fetch_array($result)) { } }
  • 非常感谢您的时间和示例。
  • 您可以在第一个 foreach() 中执行您的 while() 循环,现在我正在考虑它。我将编辑我的答案以使其更清晰
  • 是的,非常感谢编辑之前的代码使新表在表行之外生成数据。现在它工作得很好。谢谢!!
【解决方案2】:

使用这个,

function tblProperties() {
    if (isset ( $_POST ['tbl'] )) {
        $tbl = $_POST ['tbl'];
        $db = $_POST ['db'];
        $link = mysqli_connect ( 'localhost', 'root', '', $db );
     $tblarr =  explode('|', $tbl);
     for($i = 0 ; $i < sizeof($tblarr); $i++)
    {
         $qry = "DESCRIBE $tblarr[$i]";
        $result[] = mysqli_query ( $link, $qry );
     }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 2014-05-10
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多