【发布时间】:2016-12-08 04:07:31
【问题描述】:
我有一个 PHP 脚本,它查询数据库并将 json_encoded 数据返回到 javascript/jquery 文件,该文件将返回的数据处理为下拉选择框中的动态选项。
这一直运行良好。最近在我们数据库的一个字段中添加了一个 & 符号“&”:ereqs.sub_account_code -> 'HD&NO' 导致加载页面时通过 FireBug 查看语法错误。当下面的查询返回此值时,jquery/js 错误会中断响应,并且不会将任何值添加到选择框中的选项中。
错误:语法错误,无法识别的表达式:#sub_account1 option[value=HD&NO]
javascript 文件:(json 调用)
function get_sub_account_codes(instance, code){
// json call to get sub-account-codes.
$.getJSON("get-sub-account-codes.html",{code:code}, function(data){
// empty html drop-down of options that may be showing
$('#sub_account' + instance).html(''); // .empty()
$('#sub_account' + instance).val('');
// build the drop-down options
$.each(data, function(key, value){
$("#sub_account" + instance).append("<option value=\""+value.SUB_ACCOUNT_CODE+"\">"+value.SUB_ACCOUNT_CODE+"-"+value.SUB_ACCOUNT_NAME+"</option>");
});
});
}
get-sub-account-codes.html 获取数据的 PHP 代码。从js文件调用
$data = array();
$dbh = SHA_DB::getConnection('webadmin');
$sql = "select distinct sub_account_code, sub_account_name
from ereqs.kuali_account_codes
where account_code = upper(?) and
sub_account_code is not null
order by sub_account_code";
$results = $dbh->queryChecked($sql, array($code));
while($d = $results->fetchRow(DB_FETCHMODE_ASSOC))
{
$data[] = $d;
}
# return json encoded string.
print json_encode($data);
删除与号“&”不是一个可行的选择。
有没有办法检查 PHP 文件中的 & 并在将其发送回 json_encode($data) 之前以某种方式对其进行转义?还是应该在 javascript 代码中检查和更改?
感谢任何提示。
【问题讨论】:
-
该错误在哪一行被抛出?不仅仅是数字 - 而是 在此问题中发布的代码中的行。
标签: javascript jquery