Jquery使用json数组中的选项填充select字段

时间:2016-06-24 09:49:47

标签: jquery json

我有一个php脚本返回了一个类似于此

的json数组
 Caused by: java.lang.IllegalArgumentException: Target must not be null.

 at com.squareup.picasso.RequestCreator.into(RequestCreator.java:618)

 at com.squareup.picasso.RequestCreator.into(RequestCreator.java:601)

我的javascript看起来像这样

var option = '[{"mod":"Width","values":{"field":"A","value":"96}},
{"mod":"Height","values":{"field":"B","value":"33}}]';

我收到一个控制台错误说: TypeError:v为null

谁能告诉我发生了什么? JsFiddle here

3 个答案:

答案 0 :(得分:1)

嗨,请验证您的JSON然后使用那里有一些缺少的引用

for refrence https://plnkr.co/edit/FxqwzQnItGwaswVzmBir

<强> JS

var option = [
    {
        "mod": "Width",
        "values": {
            "field": "A",
            "value": "96"
        }
    },
    {
        "mod": "Height",
        "values": {
            "field": "B",
            "value": "33"
        }
    }
]

$("#mod").append($.map(option, function(o) {
  return $('<option/>', {
    value: o.values.value,
    text: o.values.field
  });
}));

答案 1 :(得分:0)

您没有有效的JSON。即使您获得了有效的JSON,也必须解析,如下所示:

// Get an object from a valid JSON string
var obj = JSON.parse(option);

// Loop through this object
for(var o in option) {
   ...
}

检查here以验证JSON

答案 2 :(得分:0)

您需要进行以下更改

var option = [{
  "mod": "Width",
  "values": {
    "field": "A",
    "value": 96
  }
}, {
  "mod": "Height",
  "values": {
    "field": "B",
    "value": 33
  }
}];

$("#mod").append($.map(option, function(v) {
  return $('<option/>', {
    value: v.values.value,
    text: v.values.value
  });
}));

Fiddle