我可以将PHP数组作为JSON编码对象传递为选择字段值并与Javascript一起使用吗?

时间:2015-02-07 14:21:27

标签: php jquery json

我有一个PHP函数,它返回数据库值以填充选择表单字段。我试图用数据库中的查询(id,name,min,max)中的所有相关数据填充选项元素的值,这样我就不必发送AJAX请求来获取其余的,所以我决定在填充选择字段之前,对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="{&quot;id&quot;:&quot;1&quot;,&quot;name&quot;:&quot;Arm&quot;,&quot;min&quot;:&quot;15000&quot;,&quot;max&quot;:&quot;25000&quot;}">Arm</option><option value="{&quot;id&quot;:&quot;3&quot;,&quot;name&quot;:&quot;Head&quot;,&quot;min&quot;:&quot;100000&quot;,&quot;max&quot;:&quot;150000&quot;}">Head</option><option value="{&quot;id&quot;:&quot;2&quot;,&quot;name&quot;:&quot;Leg&quot;,&quot;min&quot;:&quot;30000&quot;,&quot;max&quot;:&quot;45000&quot;}">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"}

1 个答案:

答案 0 :(得分:1)

错误发生在jQuery.parseJSON(jQuery(injury));。您使用未解析的JSON调用jQuery()。但jQuery期望选择器和JSON不是有效的。

尝试:jQuery.parseJSON(injury);