【发布时间】:2015-03-18 06:12:57
【问题描述】:
if (isset($_POST['continentid'])) {
$stmt = $dbh->prepare("SELECT * FROM country_tbl WHERE parent_id = ? ");
$stmt->bindValue(1, $_POST['continentid'], PDO::PARAM_STR);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
while ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$country[] = array('sysid' => $selected_row['sys_id'],'name' => $selected_row['countryname']);
}
//print_r($country);
echo json_encode($country);
//echo "312321321321";
//return $country;
}
}
}
$.ajax({
type: 'POST',
url: '../include/country.php',
dataType : "json",
data: {
continentid: id
},
success: function(data) {
for(var i = 0; i < data.length; i++) {
console.log("PAIR " + i + ": " + data[i].sysid);
console.log("PAIR " + i + ": " + data[i].name);
}
}
});
我上面有这段代码,它使用 jquery ajax 发送请求,它将返回一个 id,该 id 将用作 select 语句的参数。然后我在选择选项框上使用这些值。我已经为此here 发布了一个问题。现在可以正常工作了为国家。问题是为什么列表中的第一个值没有给出 json 值,但如果 print_r 它有值,这个设置有什么问题?
Update
如果我这样做了
print_r($country); echo json_encode($country);
对于第一个元素
Array
(
[0] => Array
(
[sysid] => 1
[code] => 140101000
[name] => China
[parentid] => 1
)
[1] => Array
(
[sysid] => 2
[code] => 140102000
[name] => Japan
[parentid] => 1
)
[2] => Array
(
[sysid] => 3
[code] => 140103000
[name] => Hongkong
[parentid] => 1
)
)
如果我这样做了
print_r($country); echo json_encode($country);
第二个元素
Array
(
[0] => Array
(
[sysid] => 1
[code] => 140101000
[name] => China
[parentid] => 1
)
[1] => Array
(
[sysid] => 2
[code] => 140102000
[name] => Japan
[parentid] => 1
)
[2] => Array
(
[sysid] => 3
[code] => 140103000
[name] => Hongkong
[parentid] => 1
)
)
[
{"sysid":"1","code":"140101000","name":"China","parentid":"1"},{"sysid":"2","code":"140102000","name":"Japan","parentid":"1"},{"sysid":"3","code":"140103000","name":"Hongkong","parentid":"1"}
]
UPDATE
我想我找到了问题,虽然我还没有找到解决方案,但我认为字符 ñ 和 ' 是他们不会为 json 返回值的原因,知道如何让它返回这些值吗?
【问题讨论】:
-
请分享你的json结构。
-
类似上面的...例如,一个是大陆列表,第一个不会返回值,但如果 print_r 我将返回值
-
在 country.php 上使用
json_encode并与问题分享输出 -
如果
print_r和您的json之间存在差异,请在问题中添加两者。所以其他人很容易发现问题 -
不同之处在于,当我执行 print_r 时,我在 ajax 成功中得到输出,但在 json 上没有输出