【问题标题】:Ajax call to webapi doesn't happen不会发生对 webapi 的 Ajax 调用
【发布时间】:2018-12-14 21:58:00
【问题描述】:

我正在关注this kudvenkat tutorial

我创建了 WebApi 项目并拥有 Get 方法。

public HttpResponseMessage Get()
{
   List<Student> students;
   List<StudentVM> studentsvm = new List<StudentVM>();
   using (SchoolEntities sc = new SchoolEntities())
   {
   students= sc.Students.ToList<Student>();
   }
        foreach (Student s in students)
        {
          StudentVM svm = new StudentVM { Sid = s.Id, Sname = s.Name };
          studentsvm.Add(svm);
        }
return Request.CreateResponse(HttpStatusCode.OK, studentsvm);
}

通过 URL 请求 http://localhost:3735/api/values 我得到数据。我什至在这里设置了一个断点。因此,当刷新上述 URL 时,断点命中。 在同一个项目中,我创建了一个 html 页面并具有以下代码。

<script type="text/javascript">
    $(document).ready(function (e)
     {
      var ulemp = $('#ulemp');
      $('#showemp').click(function () {
            $.ajax({
                type: 'GET',
                Url: 'http://localhost:3735/api/values',
                datatype: 'json',
                success: function (data, jqXHR) {
                    console.log(jqXHR);
                    ulemp.empty();
                    ulemp.append(data.value);
                },
                error: function () {
                    console.log("There is an Error");
                }
            })
        });
    });
</script>

<body>
<button id="showemp" name="showbtn"> Show Employees</button>
<button id="clear" name="clearbtn">Clear</button>
<p id="ulemp"></p>
</body>

但我没有收到任何错误或任何响应。我经历了许多与 WebApi 和 Ajax 调用相关的堆栈溢出问题。大部分问题都没有解决,部分解决的有小错误,我已经验证过了。

目前我正在使用 VS2012 和 jquery 1.7.1

如果有人能指出我所缺少的东西,我真的很感激。

【问题讨论】:

  • 这个问题你解决了吗?
  • @PrashantPimpale 当我在另一台计算机上执行相同的项目时,它运行良好。我不确定 Visual Studio 的特定实例中存在什么问题。
  • 因此,我的意思是顺便解决了。
  • 好.. 因为 我正在关注这个 kudvenkat 教程 行,只是想确保得到解决方案!对我来说,他是 .net 世界上最好的人!

标签: ajax asp.net-web-api


【解决方案1】:

您是否启用了 CorsAttribute?如果不在全局范围内或在 Get 方法上添加它

    [EnableCors(origins:"*",headers:"*",methods:"*")]
    public HttpResponseMessage Get()
    {
        //method body
    }

【讨论】:

  • 如前所述:在同一个项目中! CORS 会怎样?
  • 对不起,我的错我没看错。如果它在同一个项目中,我认为你不需要 URL:localhost:3735/api/values,只需 URL:api/value,它是你的路由方法。
  • @Mycenaean 我在这里提供了完整的 URL,因为我是为了确保这不会造成问题。
  • @Raida Adn 如果您正在观看 kudvenkat,您实际上可以在代码中看到他编写 api/controller 但在幻灯片上他提供了完整路径:D。顺便说一句,有史以来最好的老师
猜你喜欢
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2015-08-24
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
相关资源
最近更新 更多