0

我似乎无法理解 ajax 和 json

我想做一个级联下拉菜单,我试图将数据放到一个 div 开始。这是脚本

<script src="~/Scripts/jquery-ui-1.8.20.js"></script>
<script src="~/Scripts/jquery-ui-1.8.20.min.js"></script>
<script>

    $(function () {
        $('#funtiontype').change(function () {
            var selectedValue = $(this).val();

            $.ajax(
                {
                  // url: $(this).data('url'),
                  // source: "/EmployeeReps/GetDescription",
                url: "~/EmployeeReps/GetDescription",
                type: 'GET',
                cache: false,
                data: {value: selectedValue },
                success: function (result) {
                      $('#description').html(result.employeelist);
                     }
                });

            });

        });

</script>

和控制器

[AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetDescription(string value)
        {

            //get the data from DB
            var employeelist =(from s in db.tble_employeeReps where s.em_function==value 
                             select s);


            return Json(employeelist.ToList(), JsonRequestBehavior.AllowGet);
        }

HTML @using (Html.BeginForm()) {

    <fieldset>

        <div class="editor-label">Function*</div>
        <div class="editor-field">

          <select id = "funtiontype">
               <option value = "">Please Select</option>
               <option value = "Finance">Finance</option>
               <option value = "Non-Finance">Non-Finance</option>
          </select>
        </div>

        <p></p>
        <p>
            <input type="submit" value="Vote" />
        </p>
    </fieldset>
    <div id="description"></div>
}

但我正在努力获取任何数据。请任何人都可以帮助

非常感谢提前赫什

4

1 回答 1

0

控制器中的这一行:

        return Json(employeelist.ToList(), JsonRequestBehavior.AllowGet);

正在将您的员工列表更改为 JSON 字符串。字符串是一个对象数组。

在您的 ajax 调用中:

        $.ajax(
            {
              // url: $(this).data('url'),
              // source: "/EmployeeReps/GetDescription",
            url: "~/EmployeeReps/GetDescription",
            type: 'GET',
            cache: false,
            data: {value: selectedValue },
            success: function (result) {
                  $('#description').html(result.employeelist);
                 }
            });

        });

result是同一个对象数组。 result不会有一个名为employeelist. 它实际上是一组员工。

您将需要在该数组上循环并创建 HTML 以显示员工:

        $.ajax({
            url: "~/EmployeeReps/GetDescription",
            type: 'GET',
            cache: false,
            data: {value: selectedValue },
            success: function (result) {
                var employeeHTML = "";
                for(count = 0; count < result.length; count++) {
                    employeeHTML += "<p>" + result[count].EmployeeName + "</p>"; //your fields here
                }
                $('#description').html(employeeHTML);
            });
        });
于 2013-03-27T17:38:21.063 回答