繁体   English   中英

$ http.post请求在angularJS中不起作用?

[英]$http.post request not working in angularJS?

这个问题已经在这个网站上被严重回答,但是他们都没有帮助。 所以我再次问:

当我发出这样的POST请求时:

var sectionTypeVM = new Object();
        sectionTypeVM.SectionTypeId = 0;
        sectionTypeVM.Name = $scope.message;
        $http({
            method: 'POST',
            url: 'http://mtapi.azurewebsites.net/api/sectiontype',
            dataType: 'json',
            data: sectionTypeVM,
            headers: { 'Content-Type': 'application/json; charset=UTF-8' }
        }).success(function (data) {
            alert(data);
        }).error(function (data) {
            alert(data);
        });

它工作正常,但是当我尝试执行以下操作时:

        $http({
            method: 'POST',
            url: 'http://mtapi.azurewebsites.net/api/sectiontype',
            dataType: 'json',
            data: $scope.message,
            headers: { 'Content-Type': 'application/json; charset=UTF-8' }
        }).success(function (data) {
            alert(data);
        }).error(function (data) {
            alert(data);
        });

没有。 为什么我需要用javascript方法创建一个单独的对象并发送它,为什么我的angularJS对象不能直接发布(它们看起来一样)? 是服务器端错误还是什么? 有一个解释会有所帮助。

您的2个帖子之间的主要区别是,第一个发送了一个带有两个字段(名称和SectionTypeId)的对象,而第二个仅发送了$ scope.message的内容。 我可能是错的,但看起来$ scope.message是一个字符串。 但是,您正在将内容类型设置为application / json。

两者之间的区别是第一个帖子发送了这个对象

{
    SectionTypeId: 0,
    Name: [
        {"name"="abc", "id"="1"},
        {"name"="bcd", "id"="2"}
    ]
}

当第二个帖子发送这个数组时

[
    {"name"="abc", "id"="1"},
    {"name"="bcd", "id"="2"}
]

您需要重组代码,以便$ scope.message是服务器可以接受的有效json对象,或者将$ scope.message包装在与第一个示例类似的对象中。

首先是发送sectionTypeVM这是一个JavaScript对象,二是发送$scope.message这,我假设是从指定字符串sectionTypeVM.Name 两者并不相同。

尽管在此简单示例中, var sectionTypeVM = new Object()var sectionTypeVM = {}相同,但后者更清楚地说明了sectionTypeVM是对象文字的意图。 由于您要将JSON发送到服务器,因此应首选对象文字表示法。

我假设$ scope.message只是一个字符串(或数组)。 第二个示例不起作用的原因可能是因为$ scope.message不是对象文字,并且您已将json指定为期望的数据格式。 对象文字必须遵循以下格式:

var sectionTypeVM = {
      property: 'foo',
      property: 'bar'
};  

如果您想修改第二个示例以使其起作用,则可以将数据有效载荷更改为对象文字符号:

   $http({
        method: 'POST',
        url: 'http://mtapi.azurewebsites.net/api/sectiontype',
        dataType: 'json',
        data: { Name: $scope.message },
        headers: { 'Content-Type': 'application/json; charset=UTF-8' }
    })

如果您的服务器满足了第一次请求,则可以这样发布

    $http({
        method: 'POST',
        url: 'http://mtapi.azurewebsites.net/api/sectiontype',
        dataType: 'json',
        data: {SectionTypeId:0, Name: $scope.message},
        headers: { 'Content-Type': 'application/json; charset=UTF-8' }
    }).success(function (data) {
        alert(data);
    }).error(function (data) {
        alert(data);
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM