尝试使用AJAX调用填充选择标记时出现问题

时间:2015-09-27 21:47:49

标签: javascript jquery ajax

我正在开发一个用于控制库的小项目,我需要在数据库中填入一个包含所有库的select标记。为此,我创建了一个WebService,其中包含一个名为GetBibliotecas的Web方法,负责以JSON格式返回所有库;它的代码将显示在下面:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class BibUtil : WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetBibliotecas()
    {
        return JsonConvert.SerializeObject(DAOFactory.GetInstance(DAOFactory.DAOType.Biblioteca).Select());
    }
}
  

这是从WebMethod返回的结果:

     

[{"IdBiblioteca":3,"Nome":"Biblioteca FESO Campus","Endereco":"Avenida Oliveira Botelho"},{"IdBiblioteca":5,"Nome":"Biblioteca FESO Pro-Arte","Endereco":"Rua Exemplo"},{"IdBiblioteca":11,"Nome":"Biblioteca FESO Quinta do Paraíso","Endereco":"Avenida da Prata"},{"IdBiblioteca":12,"Nome":"Exemplo Library","Endereco":"Rua EX"}]

在我的视图页面上,我尝试使用AJAX,以便在页面加载后异步使用WebService方法。以下是我编码的片段:

<script>
$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "../Services/BibUtil.asmx/GetBibliotecas",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            $('#ddlLibraries').get(0).options.length = 0;
            $('#ddlLibraries').get(0).options[0] = new Option("Selecione uma biblioteca", "-1");

            $.each(data.d, function (index, item) {
                $('#ddlLibraries').get(0).options[$("#ddlLibraries").get(0).options.length] = new Option(item.Display, item.Value);
            });
        }
    });
});

但是当在浏览器上呈现页面时,控制台上会出现一些奇怪的错误:

Uncaught TypeError: Cannot use 'in' operator to search for '325' in [{"IdBiblioteca":3,"Nome":"Biblioteca FESO Campus","Endereco":"Avenida Oliveira Botelho"},{"IdBiblioteca":5,"Nome":"Biblioteca FESO Pro-Arte","Endereco":"Rua Exemplo"},{"IdBiblioteca":11,"Nome":"Biblioteca FESO Quinta do Paraíso","Endereco":"Avenida da Prata"},{"IdBiblioteca":12,"Nome":"Exemplo Library","Endereco":"Rua EX"}]

我的意图是将IdBiblioteca用作下拉列表的ID值(选择标记),并使用库名称(Nome)显示选项本身。代码有什么问题?

感谢。

1 个答案:

答案 0 :(得分:1)

无需每次都查找选项的索引和长度。可以创建所有选项,然后使用html()或在清空容器后单独追加

success: function (data) {
    // empty the <select>
    var $select = $('#ddlLibraries').empty();

    // add default to array
    data.d.unshift({
        Nome: "Selecione uma biblioteca",
        IdBiblioteca: -1
    });
    // creaate and append options
    $.each(data.d, function (index, item) {
        var $option = $('<option>').text(item.Nome).val(item.IdBiblioteca);
        $select.append($option);
    });
}

您的代码感到困惑,使用属性来创建在显示的数据中不存在的new Option