简体   繁体   English

无法通过angularjs的$ http模块将数据发布到服务器

[英]Cannot POST data to server through angularjs's $http module

I am coding using angular ajax. 我正在使用角度ajax进行编码。 The client side code is: 客户端代码是:

$http({
    method: 'POST',
    url: '----/test.php',
    data: ({'txtDeviceID': 12345678}),
    headers: {
        'Content-type': 'application/text'
    }
}).then(function successCallback(response) {
    console.log(response)
}, function errorCallback(response) {
    console.log(response)
});

The server side code is: 服务器端代码为:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With,Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
echo $_POST['txtDeviceID'];

Why can't I get the texDeviceId ? 为什么无法获取texDeviceId Thank you for your time! 感谢您的时间!

设置'Content-type':'application / json'

Your problem 你的问题

Your problem is, because you send JSON data to PHP file, but PHP expects it to be in form param format: 您的问题是,因为您将JSON数据发送到PHP文件,但是PHP希望它采用形式参数格式:

  • your client code sends {'txtDeviceID': 12345678} 您的客户代码发送{'txtDeviceID': 12345678}
  • but server code expects txtDeviceID=12345678 但是服务器代码需要txtDeviceID=12345678

To solve this you have two options, changing your client code to send data in form param format or changing your server code to expect data in JSON format. 要解决此问题,您有两个选择,更改您的客户端代码以表单参数格式发送数据,或更改服务器代码以JSON格式获取数据。

changing your your client code 更改您的客户代码

Look for response.data and change request's content-type to application/x-www-form-urlencoded , additionally you should transform your data to form format using $httpParamSerializer . 查找response.data并将请求的content-type更改为application/x-www-form-urlencoded ,另外,您应该使用$httpParamSerializer将数据转换为表单格式。

$http({
    method: 'POST',
    url: '----/test.php',       
    data: $httpParamSerializer({ 'txtDeviceID': 12345678 }),  
    // or data: "txtDeviceID=12345678",
    headers: {
        'Content-type': 'application/x-www-form-urlencoded'
    }
}).then(function successCallback(response) {
    console.log(response.data)
}, function errorCallback(response) {
    console.log(response)
});

For more info read $http docs 有关更多信息,请阅读$ http docs

The response object has these properties: 响应对象具有以下属性:

  • data – {string|Object} – The response body transformed with the transform functions. data – {string | Object} –使用转换函数转换的响应主体。
  • status – {number} – HTTP status code of the response. status – {number} –响应的HTTP状态代码。
  • headers – {function([headerName])} – Header getter function. headers – {function([headerName])} –标头获取函数。
  • config – {Object} – The configuration object that was used to generate the request. config – {Object} –用于生成请求的配置对象。
  • statusText – {string} – HTTP status text of the response. statusText – {string} –响应的HTTP状态文本。

or changing your server code. 或更改服务器代码。

To get raw submitted data you need to use file_get_contents('php://input') 要获取原始提交的数据,您需要使用file_get_contents('php://input')

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With,Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');

$_POST = json_decode(file_get_contents('php://input'), true);
echo $_POST['txtDeviceID'];

try something like this 尝试这样的事情

$http({
    method: 'POST',
    url: '----/test.php',
    data: {"txtDeviceID":12345678},
    headers: {
    'Content-type': 'application/json'
}
  }).then(function (response) {
    console.log(response)
    }, function (response) {
      console.log(response)
    });

modify your php file like this 像这样修改你的php文件

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With,Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');


$jsonstring = file_get_contents ( 'php://input' );
$arr = json_decode($jsonstring,true);
echo $arr["txtDeviceID"];

In your PHP, change echo $_POST['txtDeviceID']; 在您的PHP中,更改echo $_POST['txtDeviceID']; to echo json_encode($_POST['txtDeviceID']); echo json_encode($_POST['txtDeviceID']);

and in your controller Make sure that data is on object . 并在控制器中确保data对象上

$http({
    method: 'POST',
    url: '----/test.php',
    data: {'txtDeviceID':12345678}
  }).then(function successCallback(response) {
    // look specifically for "txtDeviceID"
    console.log(response.data.txtDeviceID)
    }, function errorCallback(error) {
      console.log(error)
    });

Use $http interceptor like the one below, it work for me 使用$ http拦截器,如下所示,它对我有用

(function(){
  angular.module('xxxxxxx').factory('sessionInjector', function() {  
      var sessionInjector = {
          request: function(config) {

              config.headers['Authorization'] = "Bearer " + sessionStorage.getItem('token');

              if(config.method == 'POST') {
                if(config.data) {
                  config.data = $.param(config.data); //jQuery magic but php likes
                }
              }

              return config;
          },
          response: function(res) {
              console.log(res);
                return res;
          }
      };
      return sessionInjector;
  });
}());

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

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