将数据表单 HTML 传递给 JS 有效的 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

谢谢

你需要对你的 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" />

更改数据两边的引号(从双引号改为单引号)

<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

还有一件事,不要用attrdata,jQuery有一个内置的方法叫做.data()

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

最新更新