【问题标题】:How to write Web API call in AngularJS or jQuery如何在 AngularJS 或 jQuery 中编写 Web API 调用
【发布时间】:2016-08-21 04:01:47
【问题描述】:

我已经创建了一个 Web API,它在我的浏览器的地址行中工作,但是当我尝试编写 AngularJS 或 jQuery 调用时,它们失败了,没有任何解释。我认为我在 URL 中没有正确的路由,或者可能是 JSON 格式问题。我有一个早期版本的 Web API,来自 AngularJS 或 jQuery 的相同调用有效。但在那个较早的版本中,我已经在路由中声明了这个动作。然后我在一个 RESTful Web API 中读到,最好的做法是省略路由中的操作并将路由基于 HTTP 方法。所以我重建了 Web API 来做到这一点,但现在我无法在客户端重新连接。有人可以在我的 URL 路由中看到错误吗?您可以测试本示例中的 URL,并在浏览器中查看数据。

注意:我想我已经解决了这个问题。我需要在我的新 Web API 中添加一个 JSON 格式化程序。这是我的第一个版本。这是迄今为止我发现的唯一区别。

            var sURL2 = "http://stevegaines.info/api/Securities?SecurityType=CASH";
            $http.get(sURL2)
                .then(function (oData)
                {
                    alert("oData = " + oData);
                    $scope.Securities = oData;
                }, function (response)
                {
                    alert("error = " + response.statusText);
                });

【问题讨论】:

  • 我认为 $http 应该发送一个对象,我总是使用 $http 之类的: var req = { method: 'GET', url: 'your url' }; $http(req).then( function successCallback(successData){}, function(errorCallback(errorData){}); 嗯,显示你的控制器和模型的源代码。是的,检查 json 格式化程序。
  • 只需将您的端点 api 地址添加到 $http.get() 而不是整个 url,使用:var sURL2 = "api/Securities?SecurityType=CASH";
  • routeconfig中定义的路由是什么?

标签: jquery angularjs asp.net-web-api


【解决方案1】:

我终于让它工作了。我认为问题出在客户端javascript上,但我也重写了Web API,所以我不确定。我知道在 javascript 中更改的一件事是我使用了 jQuery .success 方法,但我将其更改为 .then 因为 jQuery 弃用了 .success。当我这样做时,我必须使用 dataResponse 的 data 属性。只是普通的 dataResponse 是行不通的。我猜这是不同类型的对象。

            $http.get(sURL2)
                .then(function (dataResponse)
                {
                    // this doesn't work
                    // $scope.Securities = dataResponse.data.records;
                    // this doesn't work
                    // $scope.Securities = dataResponse;

                    // this works
                    $scope.Securities = dataResponse.data;
                }, function (response)
                {
                    alert("error = " + response.statusText);
                });

【讨论】:

    猜你喜欢
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 2020-08-04
    • 2018-04-05
    • 2020-07-19
    相关资源
    最近更新 更多