[英]json_encode works for integers not for strings
I am trying to pass arrays from php to js and the json_encode function works on $MID (integer array) but fails to do anything on $name (array of strings).我正在尝试将数组从 php 传递到 js,并且 json_encode 函数在 $MID(整数数组)上工作,但在 $name(字符串数组)上无法执行任何操作。
Can anybody help me understand why it won't work?有人能帮我理解为什么它不起作用吗?
$sql = "SELECT DISTINCT [materialID],[name],[categoryName],[materialResponsePerson]
FROM [SAP_Replication].[dbo].[IntranetProductResponsePerson]";
$params = array();
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
$MID = array();
$name = array();
$cName = array();
$resPerson = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
array_push($MID,$row["materialID"]);
array_push($name,$row["name"]);
array_push($cName,$row["categoryName"]);
array_push($resPerson,$row["materialResponsePerson"]);
}
echo json_encode($MID); //works and returns values
echo json_encode($name); //returns bool(false)
sqlsrv_close($conn);
Only echo one thing back to the Javascript!只向 Javascript 回显一件事! It is expecting to get one reply from your PHP code and not 4.它期望从您的 PHP 代码中得到一个答复,而不是 4。
so I would do所以我会做
echo json_encode([ 'MID' => $MID,
'name' => $name,
'cName' => $cName,
'resPerson' => $resPerson
]);
Then change your js code to read data from the right object然后更改你的 js 代码以从正确的对象读取数据
I have made a mistake when commenting the code.我在注释代码时犯了一个错误。 When I var_dump the $name variable it returns bool(false).当我 var_dump $name 变量时,它返回 bool(false)。 Later I found out that meant that json_encode doesn't support string which have 'đ','ž','...' in them so I need to convert the array to utf-8.后来我发现这意味着 json_encode 不支持包含 'đ','ž','...' 的字符串,所以我需要将数组转换为 utf-8。 Thanks everyone for the help.感谢大家的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.