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


Can I pass a PHP Array as JSON encoded object as select field value and use with Javascript?

我有一个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="{&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"}

错误在jQuery.parseJSON(jQuery(injury));中。使用未解析的JSON调用jQuery()。但是jQuery需要一个选择器,而JSON不是一个有效的选择器。

尝试:jQuery.parseJSON(injury);