如何在没有jQuery的情况下使用$http发布url编码的表单数据

How do I POST urlencoded form data with $http without jQuery?

本文关键字:http 发布 url 数据 表单 编码 情况下 jQuery      更新时间:2023-09-26

我是AngularJS的新手,首先,我想只使用AngularJS开发一个新的应用程序。

我正在尝试使用Angular应用程序中的$http对服务器端进行AJAX调用。

为了发送参数,我尝试了以下操作:

$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);
});

这是可行的,但它也在$.param中使用jQuery。为了消除对jQuery的依赖,我尝试了:

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

但这似乎失败了。然后我尝试了params:

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

但这似乎也失败了。然后我尝试了JSON.stringify:

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

我找到了这些可能的答案,但没有成功。我做错什么了吗?我确信AngularJS会提供这个功能,但是如何提供呢?

我认为您需要做的是将数据从对象转换为url参数,而不是JSON字符串。

来自Ben Nadel的博客。

默认情况下,$http服务将通过将数据序列化为JSON,然后将其与内容一起发布-类型;application/json";。当我们想将值发布为FORM时post,我们需要更改序列化算法并发布数据对于内容类型;application/x-www-form-urlencoded";。

这里的示例。

$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 () {});

更新

要使用AngularJS V1.4添加的新服务,请参阅

  • 仅使用AngularJS服务的URL编码变量

仅使用AngularJS服务的URL编码变量

使用AngularJS 1.4及以上版本,两个服务可以处理POST请求的url编码数据过程,无需使用transformRequest或使用jQuery:等外部依赖项来处理数据

  1. $httpParamSerializerJQLike-一个受jQuery的.param()(推荐(启发的序列化程序

  2. $httpParamSerializer-Angular本身用于GET请求的序列化程序

$http((示例

$http({
  url: 'some/api/endpoint',
  method: 'POST',
  data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
  }
}).then(function(response) { /* do something here */ });

查看更详细的Plunker演示


$http.post((示例

$http.post(
    'some/api/endpoint',
    data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
    {
       headers: {
         'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
      }
    }
).then(function

$httpParamSerializerJQLike$httpParamSerializer有何不同

总的来说,似乎$httpParamSerializer使用较少的";传统的";当涉及到复杂的数据结构时,url编码格式比CCD_。

例如(忽略括号的百分比编码(:

编码阵列

{sites:['google', 'Facebook']} // Object with array property
sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike
sites=google&sites=facebook // Result with $httpParamSerializer

编码对象

{address: {city: 'LA', country: 'USA'}} // Object with object property
address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike
address={"city": "LA", country: "USA"} // Result with $httpParamSerializer

所有这些看起来都是过度使用(或不起作用(。。。只需这样做:

$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
                     `&password=${ encodeURIComponent(password) }` +
                     '&grant_type=password'
).success(function (data) {

问题是JSON字符串格式,您可以在数据中使用一个简单的URL字符串:

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});

这是它应该的方式(请不要更改后端…当然不会…如果您的前端堆栈不支持application/x-www-form-urlencoded,那么就把它扔掉…希望AngularJS支持!

$http({
     method: 'POST',
     url: 'api_endpoint',
     headers: {'Content-Type': 'application/x-www-form-urlencoded'},
     data: 'username='+$scope.username+'&password='+$scope.password
 }).then(function(response) {
    // on success
 }, function(response) {
    // on error
 });

AngularJS 1.5 的魅力

各位,让我们给你一些建议:

  • 在处理$http时使用promise .then(success, error),忘记.sucess.error回调(因为它们已被弃用(

  • 从angularjs网站">您不能再使用JSON_CALLBACK字符串作为占位符来指定回调参数值的位置。">

如果你的数据模型比用户名和密码更复杂,你仍然可以这样做(如上所述(

$http({
     method: 'POST',
     url: 'api_endpoint',
     headers: {'Content-Type': 'application/x-www-form-urlencoded'},
     data: json_formatted_data,
     transformRequest: function(data, headers) {
          return transform_json_to_urlcoded(data); // iterate over fields and chain key=value separated with &, using encodeURIComponent javascript function
     }
}).then(function(response) {
  // on succes
}, function(response) {
  // on error
});

encodeURIComponent的文档可以在此处找到

如果是表单,请尝试将标题更改为:

headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";

如果它不是一个表单和一个简单的json,那么试试这个头:

headers[ "Content-type" ] = "application/json";

从$http文档中,这应该可以工作。。

  $http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
    .success(function(response) {
         // your code...
     });
$http({
    method: "POST",
    url: "/server.php",
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    data: "name='Олег'&age='28'",

}).success(function(data, status) {
    console.log(data);
    console.log(status);
});
           var request = $http({
                method: "post",
                url: "process.cfm",
                transformRequest: transformRequestAsFormPost,
                data: { id: 4, name: "Kim" }
            });
            request.success(
                function( data ) {
                    $scope.localData = data;
                }
            );

如果您有php作为后端,那么您将需要做更多的修改。。请检查此链接以修复php服务器端

虽然答案很晚,但我发现angular UrlSearchParams对我来说效果很好,它还可以处理参数的编码。

let params = new URLSearchParams();
params.set("abc", "def");
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http
.post(UrlUtil.getOptionSubmitUrl(parentSubcatId), params, options)
.catch();

这对我很有效。我使用angular作为前端,使用laravel-php作为后端。在我的项目中,angular web将json数据发送到laravel后端。

这是我的角度控制器。

var angularJsApp= angular.module('angularJsApp',[]);
angularJsApp.controller('MainCtrl', function ($scope ,$http) {
    $scope.userName ="Victoria";
    $scope.password ="password"

       $http({
            method :'POST',
            url:'http://api.mywebsite.com.localhost/httpTest?callback=JSON_CALLBACK',
            data: { username :  $scope.userName , password: $scope.password},
            headers: {'Content-Type': 'application/json'}
        }).success(function (data, status, headers, config) {
            console.log('status',status);
            console.log('data',status);
            console.log('headers',status);
        });
});

这是我的php后端laravel控制器。

public function httpTest(){
        if (Input::has('username')) {
            $user =Input::all();
            return  Response::json($user)->setCallback(Input::get('callback'));
        }
    }

这是我的laravel路由

Route::post('httpTest','HttpTestController@httpTest');

浏览器中的结果是

状态200
数据JSON_CALLBACK({"用户名":"Victoria","密码":"密码","回调":"JSON_CALLBACK"}(;js:18headers函数(c({a||(a=sc(b((;returnca[K(c(]||null:a}

有一个叫邮差的镀铬分机。您可以使用来测试后端url是否正常工作。https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en

希望我的回答能对你有所帮助。