我希望我可以将一个objets数组存储在一个隐藏的输入中。
谢谢
这是html页面中的隐藏输入:
<input type="hidden" name="idMusicians" value="[{"id":7069,"project_id":324,"name":"Gator","first_name":"Ali","instrument_id":28,"created_at":"2019-08-02 15:48:07","updated_at":"2019-08-02 15:48:07",",{"id":7070,"project_id":324,"name":"Zhette","first_name":"Annie","instrument_id":29,"created_at":"2019-08-02 15:48:07","updated_at":"2019-08-02 15:48:07",}]">
我尝试了这个,但是不起作用:
var musicians = $("#idMusicians").map(function(){
var musician = this;
return musician;
}).get();
这也没有成功:
var musicians = $("#idMusicians").data('value');
答案 0 :(得分:3)
如果输入ID,然后使用以下命令,则可以在输入中获取值:
$("#idMusicians").val();
一旦将值包含在变量中,就可以将其解析为JSON,然后将允许您遍历数组以访问其对象。但是,为了使JSON.parse()
工作,value
中的值必须是有效的JSON。目前,您的值是无效的JSON,因为它无法正确关闭第一个对象。如果您解决了此问题,则可以使用JSON.parse()
而不会出错。
请参见以下示例:
const musicians = $("#idMusicians").val();
const res = JSON.parse(musicians);
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="idMusicians" name="idMusicians" value="[{"id":7069,"project_id":324,"name":"Gator","first_name":"Ali","instrument_id":28,"created_at":"2019-08-02 15:48:07","updated_at":"2019-08-02 15:48:07"},{"id":7070,"project_id":324,"name":"Zhette","first_name":"Annie","instrument_id":29,"created_at":"2019-08-02 15:48:07","updated_at":"2019-08-02 15:48:07"}]">
答案 1 :(得分:0)
#
是id选择器,而idMusicians
是name属性。尝试将其更改为id=idMusicians
或按名称属性选择$(input[name="idMusicians"])