如何在angularjs中更改post ['Content-Type']

时间:2013-07-12 07:59:52

标签: angularjs

我想在angularjs中更改帖子['Content-Type'],所以我使用

  app.config(function($locationProvider,$httpProvider) {
$locationProvider.html5Mode(false);
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;        charset=UTF-8';
 });

,事件是

     $http.post("http://172.22.71.107:8888/ajax/login",{admin_name:user.u_name,admin_password:user.cert})
        .success(function(arg_result){

            console.log(arg_result);


        });
};
然而,结果是

Parametersapplication/x-www-form-urlencoded
{"admin_name":"dd"} 

我想要的是

Parametersapplication/x-www-form-urlencoded
 admin_name dd

那我该怎么做?

4 个答案:

答案 0 :(得分:28)

尝试:

var serializedData = $.param({admin_name:user.u_name,admin_password:user.cert});

$http({
    method: 'POST',
    url: 'http://172.22.71.107:8888/ajax/login',
    data: serializedData,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }}).then(function(result) {
           console.log(result);
       }, function(error) {
           console.log(error);
       });

答案 1 :(得分:6)

angular.module('myApp', [])
        .config(function ($httpProvider) {
            $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
            $httpProvider.defaults.headers.post['Content-Type'] =  'application/x-www-form-urlencoded';
        })

答案 2 :(得分:1)

OP正在使用Content-Type : application/x-www-form-urlencoded,因此您需要使用$httpParamSerializerJQLike将帖子数据从JSON更改为字符串

注意:没有数据属性,但是 params 属性

$http({
            method: 'POST',
            url: 'whatever URL',
            params:  credentials,
            paramSerializer: '$httpParamSerializerJQLike',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        })

此外,您可以注入序列化程序并使用 data 属性

显式使用它
.controller(function($http, $httpParamSerializerJQLike) {
....
$http({
        url: myUrl,
        method: 'POST',
        data: $httpParamSerializerJQLike(myData),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
     });

答案 3 :(得分:-3)

看看这个: How can I post data as form data instead of a request payload?

或者,您可以执行以下操作:

$http.post('file.php',{
        'val': val
    }).success(function(data){
            console.log(data);
        });

PHP

$post = json_decode(file_get_contents('php://input'));
$val = print_r($post->val,true);