簡體   English   中英

發送PHP數組到JavaScript問題

[英]Sending PHP array to JavaScript issue

我有一個AJAX POST函數,該函數運行查詢MySQL數據庫的PHP文件。 它在MySQL中使用“ CONCAT”選項,然后將接收到的每一行添加到一個數組中。 我需要將該數組從PHP轉換為JavaScript,我該怎么做呢?

我嘗試過查找它,但是沒有發現我不了解如何實際實施它,或者只是將其完全拆散而沒有用。

$sql_query = substr($sql, 0, -3);

$result = $connection->query($sql_query);

if (!$result) {
    die("Invalid Query: " . mysqli_error());
}

$rowCount = mysqli_num_rows($result);

echo "Total Bans: " . $rowCount . "\r\n";
echo "\r\n";

$bans = [];

while ($row = $result->fetch_row()) {
    for ($x = 0; $x < $rowCount; $x++) {
        array_push($bans, $row[$x]);
    }
}

如果需要的話,我將其包含在我的PHP代碼中。

我嘗試了這個:

echo(json_encode($bans));

      success: function(data) {
          document.getElementById('outputtext').innerHTML = '';
          var array = new Array();
          array = data;
          document.getElementById('outputtext').innerHTML = array;
      }

那將返回所有內容,但在它們之間添加很多“,”。

數組中索引的示例:

[05-18] Daedalus禁止EXAMPLE_USERSON(EXAMPLE_GUID / EXAMPLE_IP)

我希望將$ bans數組中的所有行都放入JavaScript數組中。

當您使用echo(json_encode($bans)); 將php數組轉換為json數組。 要在javascript中使用json,您應該首先解析該數組,如下所示

success : function(data){
    result      =   JSON.parse(data) ;  
}

現在您檢查此數據console.log(result); 通過這樣的鍵訪問特定數據

name = result.name;

您的代碼中的這個地方是錯誤的:

while ($row = $result->fetch_row()) {
    for ($x = 0; $x < $rowCount; $x++) {
        array_push($bans, $row[$x]);
    }
}

因為您使用for循環循環了槽記錄, while再次循環for while以下時間使用:

while ($row = $result->fetch_row()) {
   array_push($bans, $row);
}

將拉出所有行,並且不包含空值。

在您的情況下,如果數據庫返回中只有一列,則應使用:

while ($row = $result->fetch_row()) {
       array_push($bans, $row[0]);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM