[英]Binding values to HTML dropdownlist using JQuery with ASP.NET MVC WebAPI - Cannot read property '0' of undefined
I am trying to populate values for html drowpdown using JQuery from webapi url. 我试图使用webapi url中的JQuery填充html drowpdown的值。 JSON returns value and I've verified it using alert function.
JSON返回值,我使用alert函数验证了它。 But, when I bind those into dropdown it is not populating the values.
但是,当我将它们绑定到下拉列表时,它不会填充值。
Chrome developer tool console shows err: Chrome开发人员工具控制台显示错误:
@section scripts {
<script src="~/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.8.24.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var testDdl = $('#test');
$.ajax({
url: "/api/Values",
type: "Get",
success: function(data) {
for (var i = 0; i < data.length; i++) {
testDdl.append($("<option/>"), {
value: this.data[i],
html: this.data[i]
});
}
},
error: function(msg) { alert(msg); }
});
});
</script> }
<body>
<form>
<select id="test"></select>
</form> </body>
Please help me to resolve this. 请帮我解决这个问题。
If you are certain that the data object is correct (it would have to just be an array of strings) this should work: 如果您确定数据对象是正确的(它必须只是一个字符串数组),这应该工作:
success: function(data) {
for (var i = 0; i < data.length; i++) {
var option = $("<option/>");
option.attr("value", data[i]).text(data[i]);
testDdl.append(option);
}
},
Here is a fiddle of it in action: http://jsfiddle.net/aq8X5/5/ 以下是它的一个小提琴: http : //jsfiddle.net/aq8X5/5/
Iterate through the result with $.each
. 使用
$.each
迭代结果。
$.each(data, function(key, value) {
console.log(key);
console.log(value);
}
What you should pass to testDdl.append
depends on what your JSON looks like. 你应该传递给
testDdl.append
取决于你的JSON是什么样的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.