【问题标题】:Differentiate between HTTP request and Ajax request区分 HTTP 请求和 Ajax 请求
【发布时间】:2014-06-28 02:00:27
【问题描述】:

我目前正在研究 ASP.NET WebApi 和 Angularjs

WebApi 有一个方法

 [System.Web.Http.AcceptVerbs("POST")]
        [System.Web.Http.HttpPost]
        public HttpResponseMessage SearchAddress(SearchDetails searchDetail)
        {
            //13.03993,80.231867
            try
            {
                if (!WebSecurity.IsAuthenticated)
                {
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotAcceptable);
                    return response;
                }
                List<CollegeAddress> CollegeAddress = addressService.GetAddressFromDistance(17.380498, 78.4864948, 2000);
                HttpResponseMessage responseData = Request.CreateResponse(HttpStatusCode.Accepted, CollegeAddress);
                return responseData;
            }
            catch (Exception e)
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound);
                return response;
            }
        }

我必须从客户端调用这个方法。

当我使用Ajax调用这个方法时,它不起作用,如果我使用Ajax,方法参数searchDetail总是为空。

$.ajax({
            method: 'POST',
            url: rootUrl + '/api/Address/SearchAddress',
            async: false,
            data: searchDetail,
            type: "json",
            headers: {
                'Content-Type': "application/json; charset=utf-8"
            }
        }).success(function (response) {
            return response;

        }).error(function () {
            toastr.error('Somthing is wrong', 'Error');
        })

但是当我通过HTTP 请求调用该方法时,它正在工作。

 $http({
            method: 'POST',
            url: rootUrl + '/api/Address/SearchAddress',
            data: searchDetail,
            headers: {
                'Content-Type': "application/json; charset=utf-8"
            }
        }).success(function (response) {
            toastr.success('Account Created successfully!', 'Account Created');
            return response;
        }).error(function () {
            toastr.error('Somthing is wrong', 'Error');
        })

为什么?它们之间有什么区别?为什么 Ajax 不工作而 HTTP 工作?

【问题讨论】:

  • 我确定 some1 会回答,...但是你为什么将 $.ajax 与 Angular 项目混合使用?我会完全删除 jQuery。
  • @MaximShoustin ,因为http不支持async:false对象。我想同步调用一些方法。所以我用了一段时间的 Ajax
  • 我认为是服务器。如果他没有配置消费application/json 你不能发送这样的请求。和http?默认情况下。

标签: javascript ajax angularjs http asp.net-web-api


【解决方案1】:

jQuery 的 ajax() 发送 Content-type 的数据:x-www-form-urlencoded
Angular 的 $http 发送 Content-type 的数据:application/json

您的服务器显然需要 JSON,但您为此设置了错误的 $.ajax() 调用。

根据the docs

  • method 属性似乎不存在。
  • type 属性应该确定请求的类型(例如“GET”、“POST”等)。
  • 要将默认内容类型更改为application/json,您可以使用contentType 属性。

我自己没有尝试过,但是这样的东西应该可以工作:

$.ajax({
  type: 'POST',
  url: rootUrl + '/api/Address/SearchAddress',
  async: false,
  data: searchDetail,
  contentType: 'application/json; charset=utf-8'
});

【讨论】:

  • Angular's $http sends the data with Content-type: application/json 。没关系。但它不起作用,如果我在 Ajax 请求中手动添加了标头。
  • 请阅读我对代码中各种问题的回答。您使用的 type 值无效。例如,这可以强制默认类型为 GET 等。
  • 如果您想了解更多信息,可以打开 DevTools -> Netword 选项卡并捕获 2 个请求。然后你可以看到它们有什么不同(在方法、请求 URL、标头、内容等方面)。
  • 好的 +1 为该文档,谢谢!
【解决方案2】:

首先你要复制 HttpPost,所以只保留第二个(并删除命名空间) 其次,您希望搜索详细信息来自正文,因此请使用 [FromBody] 进行装饰

    [HttpPost]
    public HttpResponseMessage SearchAddress([FromBody]SearchDetails searchDetail)
    {

【讨论】:

    【解决方案3】:
    $.ajax({
            method: 'POST',
            url: rootUrl + '/api/Address/SearchAddress',
            async: false,
            data: searchDetail,
    

    我假设searchDetail 是一个对象。这就是文档对data 属性的评价:

    ...如果还不是字符串,则将其转换为查询字符串。

    因此,如果服务器需要 JSON,那么您必须先将其转换为 JSON:

    data: JSON.stringify(searchDetail),
    

    正如@ExpertSystem 指出的,您必须将method 更改为type

    【讨论】:

      猜你喜欢
      • 2011-06-20
      • 2012-04-14
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 2016-12-28
      • 2015-11-11
      相关资源
      最近更新 更多