![](/img/trans.png)
[英]How to pass the select box value as an array using AJAX from one page to another in PHP?
[英]How to pass the value of more then one 1 elements in an array from ajax to PHP?
實際上,我通過循環和數組獲取具有相同 id 的按鈕的值,我想將這些值從 ajax 傳遞給 php,但問題是它只顯示最后一個元素的值?
function remove() {
var elms = document.querySelectorAll("[id='botn']");
for (var i = 0; i < elms.length; i++)
var datastring=elms[i].value;
console.log(datastring);
$.ajax({
url: 'php/del_beacon.php',
type: 'post',
data: {data:datastring},
success: function(response) {
}
});
}
當我使用 alert(elms[i].vlaue) 然后它會顯示所有選定按鈕的值 這是我的 php 文件
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="beelist";
$conn=mysqli_connect($servername,$username,$password,$dbname);
error_reporting(0);
$connDB= mysqli_select_db($conn,'beelist');
$myArray = $_POST['data'];
echo $myArray;
?>
您只在datastring變量中存儲一個值,因為它是一個字符串變量。
for (var i = 0; i < elms.length; i++)
var datastring = elms[i].value;
對於此循環的每個元素,都重寫變量,這就是為什么僅保存最后一個值的原因。
將其更改為數組,然后通過push()
向其提供值。 然后,您應該在PHP中使用整個數組:
var datastring = [];
for (var i = 0; i < elms.length; i++)
datastring.push(elms[i].value);
您僅獲得最后一個元素,因為每次循環執行時都要重新分配值。
您需要使用push
方法。
var data.push(elms[i].value);
由於您正在通過ajax獲取所選數據的所有值。 PHP是您遇到問題的地方。 在您的php代碼中,您未指定要對發布的數據執行的操作,例如插入,更新或刪除操作。
無論如何在php中,您都需要按照以下代碼遍歷發布的數據
foreach($myArray as $pid){
echo $pid;
}
下面的代碼假定您要遍歷發布的數據以基於posts_id從posts表中刪除記錄
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="beelist";
$conn=mysqli_connect($servername,$username,$password,$dbname);
error_reporting(0);
$connDB= mysqli_select_db($conn,'beelist');
$myArray = $_POST['data'];
//loop through your post and then insert or delete or update records
foreach($myArray as $pid){
// Delete record
$query = "DELETE FROM posts WHERE id=".$pid;
mysqli_query($con,$query);
echo $pid;
}
?>
讓我知道您是否仍然遇到任何問題。
在您的代碼中,您要做的是
var datastring = elms[i].value; // Your problem is here
在這里,您正在聲明數據字符串,因此您將獲得數據中的最后一個值。 相反,您可以將值推送到數組中,然后將數組轉換為 JSON,然后像這樣通過 ajax 調用將其發送到 php。
function remove(){
var elms = document.querySelectorAll("[id='botn']");
var datastring = [];
for (var i = 0; i < elms.length; i++)
{
datastring.push(elms[i].value);
console.log(datastring);
}
var myData = JSON.stringify(datastring);
$.ajax({
url: 'php/del_beacon.php',
type: 'post',
data: {data:myData},
success: function(response) {
}
});
}
然后在您的 php 代碼中,您可以再次通過 php json_decode 中的json_decode() 函數將 json 轉換為數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.