【问题标题】:Cannot POST data to server through angularjs's $http module无法通过 angularjs 的 $http 模块将数据发布到服务器
【发布时间】:2016-10-27 01:27:57
【问题描述】:

我正在使用 Angular ajax 进行编码。客户端代码是:

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

服务器端代码为:

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'];

为什么我无法获得texDeviceId?感谢您的宝贵时间!

【问题讨论】:

  • 试试data: {'txtDeviceID':12345678}(即不带括号)和'Content-type': 'application/json'
  • 您可能想使用json_encode发回数据
  • @ADyson 我做了它仍然显示错误
  • @Debojyoti 你得到什么错误?
  • @gevorg 没有通过服务器发送任何值

标签: javascript php angularjs ajax angularjs-http


【解决方案1】:

你的问题

您的问题是,因为您将 JSON 数据发送到 PHP 文件,但 PHP 期望它是表单参数格式:

  • 您的客户端代码发送{'txtDeviceID': 12345678}
  • 但是服务器代码需要txtDeviceID=12345678

要解决这个问题,您有两个选择,将您的客户端代码更改为以表单参数格式发送数据,或者将您的服务器代码更改为期望 JSON 格式的数据。

更改您的客户代码

查找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)
});

更多信息请阅读$http docs

响应对象具有以下属性:

  • data – {string|Object} – 使用 变换函数。
  • status – {number} – 响应的 HTTP 状态代码。
  • headers – {function([headerName])} – 标头获取函数。
  • config – {Object} – 用于生成的配置对象 请求。
  • statusText – {string} – 响应的 HTTP 状态文本。

或更改您的服务器代码。

要获取原始提交数据,您需要使用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'];

【讨论】:

  • 但我可以在 console.log(response) 中看到 data 属性的值为空
  • @Debojyoti 明白了,您的问题出在标题中,因为您没有为内容类型设置正确的标题,请使用此'Content-type': 'application/x-www-form-urlencoded'
  • @Debojyoti 另外您需要使用$httpParamSerializer 将提交的数据转换为表单格式。
  • @Debojyoti 有一个替代方案,您可以更改您的服务器代码。
【解决方案2】:

设置“内容类型”:“应用程序/json”

【讨论】:

    【解决方案3】:

    试试这样的

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

    像这样修改你的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"];
    

    【讨论】:

      【解决方案4】:

      在您的 PHP 中,将 echo $_POST['txtDeviceID']; 更改为 echo json_encode($_POST['txtDeviceID']);

      在你的控制器中确保dataobject上。

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

      【讨论】:

        【解决方案5】:

        像下面这样使用 $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;
          });
        }());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-09-02
          • 2014-03-22
          • 1970-01-01
          • 2019-02-06
          • 1970-01-01
          • 1970-01-01
          • 2016-03-31
          • 1970-01-01
          相关资源
          最近更新 更多