我有一个PHP函数,它返回数据库值来填充选择表单字段。我正试图用数据库中查询的所有相关数据(id、name、min、max)填充选项元素的值,这样我就不必发送AJAX请求来获取其余数据,所以我决定在填充select字段之前对php数组进行json_encode。
相关PHP:
$items[] = array( "text" => $injury['name'], "value" => json_encode($injury) );
PHP的HTML输出:
<select name="input_2" id="input_2_2" class="medium gfield_select" tabindex="4"><option value=" ">Select an Injury</option><option value="{"id":"1","name":"Arm","min":"15000","max":"25000"}">Arm</option><option value="{"id":"3","name":"Head","min":"100000","max":"150000"}">Head</option><option value="{"id":"2","name":"Leg","min":"30000","max":"45000"}">Leg</option></select>
在javascript方面,我使用jQuery获得如下选项的值:
`jQuery(injuryClass).on("change", function () {
var injurySelect = jQuery(this);
injury = injurySelect.val();
var results = jQuery.parseJSON(jQuery(injury));
console.log(results)
我得到一个控制台错误:
uncaught error: syntax error, unrecognized expression: {"id":"1","name":"Arm","min":"15000","max":"25000"}
错误在jQuery.parseJSON(jQuery(injury));
中。使用未解析的JSON调用jQuery()
。但是jQuery需要一个选择器,而JSON不是一个有效的选择器。
尝试:jQuery.parseJSON(injury);