无法将String强制转换为Json Jquery

时间:2017-07-11 19:47:14

标签: jquery jquery-select2

Select2中的数据使用静态数据正确加载

 $('#placeSelect').select2({
            width: '100%',
            allowClear: true,
            multiple: true,
            maximumSelectionSize: 2,
            placeholder: "Click here and start typing to search.",
            data:  
                [{ id: "1", text: "Afghanistan" }, { id: "2", text: "Africa CAMEU region, nes" }]

        });

当我尝试使用字符串使其动态化时。

var _stringJson= '[{id:"1","text":"Afghanistan"},{id:"2","text":"Africa CAMEU region, nes"}]'

 json = JSON.parse(_stringJson);
 $('#placeSelect').select2({
            width: '100%',
            allowClear: true,
            multiple: true,
            maximumSelectionSize: 2,
            placeholder: "Click here and start typing to search.",
            data:json 

        });

现在正在工作。 已更新

 var _stringJson= '[{id:"1",text:"Afghanistan"},{id:"2",text:"Africa CAMEU region, nes"}]'

。通过

var _stringJson= '[{id:"1","text":"Afghanistan"},{id:"2","text":"Africa CAMEU region, nes"}]'

1 个答案:

答案 0 :(得分:0)

您的代码中有两个错误。

  1. 报价不正确" s。
  2. 字符串的字符串化!
  3. 你需要:

    // Quotes
    var _stringJson= '[{"id":"1","text":"Afghanistan"},{"id":"2","text":"Africa CAMEU region, nes"}]';
    // Use Parse
    json = JSON.parse(_stringJson);