我创建了一个php
脚本,在postgres数据库上执行select
语句。我将结果转换为json字符串,并使用<? echo $a; ?>
行将其传递给javascript
变量。
问题我无法解决的是,我的json
从php
包含波兰字符(utf-8
)编码,当javascript
得到这个值我得到Uncaught SyntaxError: Unexpected identifier
,它是完全好的,因为字符串没有转义。
我是这样做的:
php
生成json:
<? $result_json = json_encode($result); ?>
以及如何将其传递给js:
options_json='<? echo $result_json; ?>';
当我在浏览器中调试我的options_json
看起来像:
options_json='[{"code":"za'u0105e ba'u0144stre.".....
我试过escape()
utf8_encode()
和addslashes()
。首先没有结果,addslashes()
函数删除了错误,但它破坏了json
结构,因此我无法将其还原。
简单地尝试返回json编码的值,如以下示例:
$arr_rslt=array();
$query=" Select col1,col2,col3 from tbl";
$result = mysql_query($query);
while( $row = mysql_fetch_array( $result ) )
{
$arr_rslt[] = $row;
}
echo json_encode($arr_rslt);
如果您使用$。Ajax或$。Post然后在它们的回调中操作这个。也可以在$.ajax.
中使用它。contentType: "application/json; charset=UTF-8",
这可能对您有用,我正在使用下面的函数来编码那些具有阿拉伯文本的数组。试试下面的函数。我不是在处理斜杠
public function utf8_encode_all($dat) // -- It returns $dat encoded to UTF8
{
if (is_string($dat)) return utf8_encode($dat);
if (!is_array($dat)) return $dat;
$ret = array();
foreach($dat as $i=>$d) $ret[$i] = $this->utf8_encode_all($d);
return $ret;
}