【问题标题】:How to fill a select list with AJAX?如何使用 AJAX 填充选择列表?
【发布时间】:2015-07-04 01:57:13
【问题描述】:

我想用 AJAX 从选择中填充选项。我做错了什么?

这是我视图中的代码:

 $(function() {
    $.getJSON("Animes/GetCategories", null, function(data) {
        var options = '';
        for (var x = 0; x < data.length; x++) {
            options += '<option value="' + data[x]['CategoryID'] + '">' + data[x]['CategoryNom'] + '</option>';
        }
        console.log(options);
        $('#lstCat').html(options);

    });
});

我的控制器中的代码:

public JsonResult GetCategories() {
    var affCat = from cats in db.Categories
    select new {
        CategoryID = cats.CategoryID,
        CategoryNom = cats.CategoryNom
    };

    return Json(affCat, JsonRequestBehavior.AllowGet);
}

我的视图中选择的代码:

<select id="lstCat">
    //Don't know what to place in the select
    <option>?</option>
</select><br />

【问题讨论】:

  • 哦,天哪...这是一个可怕的组合 js 框架的混乱。这里真的有 Angular 吗?如果是这样,根本没有理由做这样的 jQuery。

标签: c# jquery ajax model-view-controller


【解决方案1】:

当你使用 Angularjs 时,尽量使用 to 来代替 jquery 混合

这样试试

Js

var app = angular.module("app", []);
app.controller("myCtrl", ["$scope", function($scope) {
    $scope.categoryList = [];
    $.getJSON("Animes/GetCategories", null, function(data) {
        $scope.categoryList = data;
    });
}]);

HTML

<div ng-app="app" ng-controller="myCtrl">
   <select id="lstCat" ng-options="category.CategoryID as category.CategoryNom for category in categoryList">
   </select>
</div>

顺便说一句,对于 html jquery 有 .html() 附加 html 。 .val() 如果仅用于控件

喜欢这个

$('#lstCat').html(options);

并从您的 html 中删除选项

这样

<select id="lstCat">
</select>

【讨论】:

  • 这是我的错,我添加了 Angularjs 标签,但我没有使用它。我不知道我为什么添加它
  • 然后尝试我在回答中提到的第二个建议。 $('#lstCat').html(options);
  • 它不工作,我将我的代码粘贴在顶部,我不知道如何继续,我真的厌倦了这个不能正常工作的东西
  • console.log(options); 打印是什么?你能提供那个截图吗?
【解决方案2】:

val不用于添加html。

代替:

$('#lstCat').val(options); 

尝试:

$('#lstCat').html(options);

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多