【问题标题】:jquery each item not definedjquery每个项目未定义
【发布时间】:2018-09-05 17:12:59
【问题描述】:

我的 WebApi 正在返回以下 JSON 对象:

[
{
    "Department_Id": 5,
    "Department_Description": "Test API 1"
},
{
    "Department_Id": 6,
    "Department_Description": "Test API 2"
},
{
    "Department_Id": 7,
    "Department_Description": "Test API 3"
}
]

在我使用 asp.net 的网络表单中,我有以下代码:

<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: "api/TicketDepartments/GetTicketDepartmentsComboBoxAsync",
            data: "{}",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            async: false,
            success: function (data) {
                var select = $("#ddlDepartment");

                if (data) {
                    $(data).each(function(index, item) {
                        select.append($(" 
<option>").val(item.Value).text(item.Text));
                    });
                }
            },
            error: function (data) {
                alert("An error has occurred during processing your 
 request.");
            }
        });
    });
   </script>

但是,每当我尝试运行代码时,都会收到 "item is not defined" 错误。

我正在尝试填充

Select department :
    <asp:DropDownList ID="ddlDepartment" runat="server">
    </asp:DropDownList>

带有department_description 和department_id 以便以后可以在程序中使用。

我不确定此错误的含义或它的来源。欢迎任何帮助。

【问题讨论】:

    标签: jquery asp.net webforms


    【解决方案1】:

    .each() 方法用于循环遍历包含 DOM 元素的 jQuery 集合。如果你想遍历一个普通的数组或对象,你应该使用$.each()函数。

    $.each(data, function(index, item) {
        ...
    }
    

    此外,您的对象中的属性是 Department_IDDepartment_Description,而不是 ValueText

    【讨论】:

      【解决方案2】:

      我认为你的代码应该是:

      select.append($("<option>").val(item.Department_Id).text(item.Department_Description));
                          });
      

      【讨论】:

      • 错误是抱怨item,而不是属性名称。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      相关资源
      最近更新 更多