笑故挽风 2014-07-12 06:58 采纳率: 100%
浏览 357
已采纳

如何在没有 jQuery 的情况下使用 $http 来发布经过 urlencoded 的表单数据?

I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.

I am trying to make an AJAX call to the server side, using $http from my Angular App.

For sending the parameters, I tried the following:

$http({
    method: "post",
    url: URL,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
    console.log(result);
});

This is working, but it is using jQuery as well at $.param. For removing the dependency on jQuery, I tried:

data: {username: $scope.userName, password: $scope.password}

but this seemed to fail. Then I tried params:

params: {username: $scope.userName, password: $scope.password}

but this also seemed to fail. Then I tried JSON.stringify:

data: JSON.stringify({username: $scope.userName, password: $scope.password})

I found these possible answers to my quest, but was unsuccessful. Am I doing something wrong? I am sure, AngularJS would provide this functionality, but how?

转载于:https://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http-without-jquery

  • 写回答

11条回答 默认 最新

  • YaoRaoLov 2014-07-25 21:19
    关注

    I think you need to do is to transform your data from object not to JSON string, but to url params.

    From Ben Nadel's blog.

    By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

    Example from here.

    $http({
        method: 'POST',
        url: url,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function(obj) {
            var str = [];
            for(var p in obj)
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            return str.join("&");
        },
        data: {username: $scope.userName, password: $scope.password}
    }).then(function () {});
    

    UPDATE

    To use new services added with AngularJS V1.4, see

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥50 用AT89C52单片机设计一个温度测量与控制电路
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题