将数据表格HTML传递给JS有效的JSON数据

时间:2014-12-10 01:45:50

标签: jquery html json

我有表单编辑数据和我的输入:

<input type="text" id="mySelectID" data-initvalue="[{"id":"1","text":"Value 1"},{"id":"2","text":"Value 2"}]" name="category" />

我有js功能:http://jsfiddle.net/87xpB/54/

AjaxCombo("mySelectID", "ajax.php?get=categories", "multival");

我查看控制台:

Uncaught Error: Syntax error, unrecognized expression:

html中有效的JSON如何传递给JS

thankyou

2 个答案:

答案 0 :(得分:1)

您需要对您的JSON字符串进行html编码。然后你的标签看起来像:

<input type="text" id="mySelectID" data-initvalue="[{&quot;id&quot;:&quot;1&quot;,&quot;text&quot;:&quot;Value 1&quot;},{&quot;id&quot;:&quot;2&quot;,&quot;text&quot;:&quot;Value 2&quot;}]" name="category" />

答案 1 :(得分:1)

更改数据周围的引号(从双引号到单引号)

<input type="text" id="mySelectID" data-initvalue='[{"id":"1","text":"Value 1"},{"id":"2","text":"Value 2"}]' name="category" />

另外,看着你没有正确使用选择器的小提琴,它应该是:

AjaxCombo("#mySelectID", "ajax.php?get=categories", "multival");
//         ^here

另外,不要将attr用于data,jQuery有一个内置方法,称为.data()

// From this:
$(elem).attr("data-initvalue");
// To this:
$(elem).data("initvalue");