【问题标题】:Get(int) asp.net wep api获取(int)asp.net web api
【发布时间】:2017-03-30 03:42:24
【问题描述】:

我现在真的对我的 web api 感到困惑。这是我的 Get 方法代码:

public Employee Get(int id)
{
            using (EmployeeDBEntities entities = new EmployeeDBEntities())
            {
                return entities.Employees.FirstOrDefault(e => e.ID==id);
            }
        }   

我使用 jquery ajax 来获得:

$(document).ready(function () {
    $('#btn').click(function () {
        $.ajax({
            url: 'api/employees/1',
            method: 'GET',

            success: function (data) {
                $('#ul').empty();
                $.each(data, function (index, value) {
                    var row = $('<tr><td>' + value.ID + '</td><td>'
                        + value.FirstName + '</td><td>'
                        + value.LastName + '</td><td>'
                        + value.Gender + '</td><td>'
                        + value.Salary + '</td></tr>');
                    $('#ul').append(row);
                });
            }
        });
    });
});

当我运行它时,它只是返回了很多“未定义”。但是,当我在浏览器中运行“http://localhost:52178/api/employees/1”时,我得到了我想要的正确 xml。任何人都可以帮助我吗?

【问题讨论】:

    标签: jquery ajax asp.net-web-api get


    【解决方案1】:

    尝试将您的 Ajax 调用中的 URL 更新为“/api/employees/1” - 它具有前导斜杠

    【讨论】:

    • 我发现了问题!不是url,是成功的函数:function(data)。在函数内部,它不必执行 $.each,只需附加数据及其属性即可。
    • @MinxuanZhang 太棒了!很高兴你想通了
    【解决方案2】:

    在 ajax 选项中使用 contentType: "application/json; charset=utf-8"

     $.ajax({
            url: 'api/employees/1',
            method: 'GET',
            contentType: "application/json; charset=utf-8",/*use this option*/
            success: function (data) {
                $('#ul').empty();
                $.each(data, function (index, value) {
                    var row = $('<tr><td>' + value.ID + '</td><td>'
                        + value.FirstName + '</td><td>'
                        + value.LastName + '</td><td>'
                        + value.Gender + '</td><td>'
                        + value.Salary + '</td></tr>');
                    $('#ul').append(row);
                });
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-12
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多