如何使用AngularJS在http请求中发送参数?

如何使用AngularJS在http请求中发送参数?,angularjs,Angularjs,我正在使用以下代码: $http({ method: 'GET', url: '/Admin/GetTestAccounts', data: { applicationId: 3 } }).success(function (result) { $scope.testAccounts = result; }); 代码将以下内容发送到我的服务器: http://127.0.0.1:81/Admin/GetTestAccounts 当我的MVC控制器收到此信息时:

我正在使用以下代码:

$http({
    method: 'GET',
    url: '/Admin/GetTestAccounts',
    data: { applicationId: 3 }
}).success(function (result) {
    $scope.testAccounts = result;
});
代码将以下内容发送到我的服务器:

http://127.0.0.1:81/Admin/GetTestAccounts
当我的MVC控制器收到此信息时:

[HttpGet]
public virtual ActionResult GetTestAccounts(int applicationId)
{
    var testAccounts =
        (
            from testAccount in this._testAccountService.GetTestAccounts(applicationId)
            select new
            {
                Id = testAccount.TestAccountId,
                Name = testAccount.Name
            }
        ).ToList();

    return Json(testAccounts, JsonRequestBehavior.AllowGet);
}
它抱怨没有applicationId

参数字典包含方法的非null类型“System.Int32”的参数“applicationId”的null条目

有人能解释为什么applicationId没有作为参数发送吗?之前,我使用以下非角度代码执行此操作,它工作得很好:

$.ajax({
    url: '/Admin/GetTestAccounts',
    data: { applicationId: 3 },
    type: 'GET',
    success: function (data) {
        eViewModel.testAccounts(data);
    }
});

好的,我会尽力回答这个问题

我认为问题在于angularjs假定传递到http的数据将是URL编码的。我不知道为什么angular在有对象的情况下不隐式序列化它。因此,您必须自己对其进行编码:

 $http({
       method: 'GET',
       url: '/Admin/GetTestAccounts',
       data: 'applicationId=3'
       })
或者使用jQuery参数为您编码:

$http({
     method: 'GET',
     url: '/Admin/GetTestAccounts',
     data: $.param({ applicationId: 3 })
     })

如果不想使用jQuery的$.param,可以使用$http的param字段序列化对象

var params = {
    applicationId: 3
}

$http({
    url: '/Admin/GetTestAccounts',
    method: 'GET',
    params: params
});

这有用吗@Dave-我看到了你给我的链接,现在我更困惑了:-(看看浏览器控制台网络选项卡中使用的url..它是什么样子?@Gemma你试过使用jQuery param
$.param({applicationId:3})吗
?为什么不直接将应用程序id附加到查询字符串中的url?这是angularjs的实现。当涉及日期对象时,参数的url编码会给我带来麻烦。序列化使用字符“%22”(双引号)填充日期,这导致WebAPI/MVC的modelbinder无法反序列化日期。我已经在Github上提交了一个问题,这在1.3.16中得到了修复。这在矩.js中没有得到修复。因此,如果使用它,请确保使用.toDate()。jQuery的实现:Angular的实现:基于他们对
Angular.extend()的讨论
我猜他们不喜欢实现深度复制等。同样,您可以实现浅层API查询设计或使用JSON请求如果在
GET
请求中不使用
数据,则使用
params
GET Error:$未在$.param附近定义