[英]ForEach Array Javascript
I have an array in PHP and I would like to loop through it. 我在PHP中有一个数组,我想遍历它。
Unfortunately, the array gives back this in JavaScript: 不幸的是,该数组在JavaScript中返回了此代码:
Array
(
[data] => 12,11,2,5,6,7,8,9,10,13,14,15,16,17,18
[0] => 12,11,2,5,6,7,8,9,10,13,14,15,16,17,18
)
And not: 并不是:
var myvar = [10, 11, 12, ...];
So I cannot loop through it. 所以我无法遍历它。 Any suggestions?
有什么建议么?
<?php
include("connection.php");
$query = $handler->query(' SELECT data FROM lista where id=1;');
$query->setFetchMode(PDO::FETCH_BOTH/*, 'CreaPrezzi'*/);
$r = $query->fetch();
print_r($r);
$.ajax({
type:"POST",
url:"getSortable.php"
}).done(function (list) {
var sortedList = list;
sortedList.forEach(function(id) {
$("#" + id).appendTo("#sortable")
})
})
That kind of output is indeed what you get with print_r
. 这种输出确实是您通过
print_r
获得的。 Instead use json_encode
as follows: 而是使用
json_encode
,如下所示:
echo json_encode($r[0]);
Then in JavaScript indicate that your are expecting JSON: 然后在JavaScript中指示您正在使用JSON:
$.ajax({
type:"POST",
url:"getSortable.php",
dataType: "json" // <!-- add this
}).done( // ...etc
As $r[0]
(in PHP) is a plain string, you'll need to split it into an array, either in PHP, or in JavaScript. 由于
$r[0]
(在PHP中)是纯字符串,因此您需要将其拆分为数组,无论是在PHP中还是在JavaScript中。 In PHP that could be done with explode
: 在PHP中可以通过
explode
完成:
echo json_encode(explode(",", $r[0]));
Or with JavaScript (but then use the first PHP version) you can use split
: 或使用JavaScript(但使用第一个PHP版本),则可以使用
split
:
var sortedList = list.split(',');
<?php
include("connection.php");
$query = $handler->query(' SELECT data FROM lista where id=1;');
$query->setFetchMode(PDO::FETCH_BOTH/*, 'CreaPrezzi'*/);
$r = $query->fetch();
echo json_encode($r);
$.ajax({
type:"POST",
url:"getSortable.php"
}).done(function (list) {
var sortedList = list;
sortedList.forEach(function(id) {
$("#" + id).appendTo("#sortable")
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.