无法获得与AngularJS post方法正确的数据 [英] unable to get proper data with AngularJS post method

查看:144
本文介绍了无法获得与AngularJS post方法正确的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次与AngulerJS。我试图 POST 数据发送到服务器。

this is my 1st time with AngulerJS. I'm trying to POST data to the server.

AngularJS code

 var app = angular.module("myApp", []);
var BASE_URL = "http://localhost/project/api/Data/";

var GET_DATA = BASE_URL+"get_data";
console.log(GET_DATA);
app.controller('myCtrl', function($scope, $http) {
var inputs = { "user_id": "3"};
var config = {
              headers : {
                  'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
              }
          }
$http.post(GET_DATA , inputs, config)
          .success(function (response, status, headers, config) {
              $scope.content = response.error;
              $scope.statuscode = response.status;
              $scope.statustext = response.statusInfo;
              console.log(response);    
          })
          .error(function (data, status, header, config) {
              $scope.ResponseDetails = "Data: " + data +
                  "<hr />status: " + status +
                  "<hr />headers: " + header +
                  "<hr />config: " + config;
          });

});

这code为发布数据到服务器,但与一些有线格式。下面是我的的print_r($ _ POST); 结果:

This code is posting data to the server, but with something wired format. Below is my print_r($_POST); result :

Array
(
    [{"user_id":"3"}] => 
    [0] => 
)

这是错误的结果,我期待像

this is wrong result, I am expecting something like

Array
(
    user_id => 3
)

请注意:我使用codeIgniter框架在服务器端

Note : I'm using CodeIgniter framework at server side.

推荐答案

您可以发送您的文章数据 JSON

You can send your post data in json:

$http.post(GET_DATA , {"user_id": "3"})
      .success(function (response, status, headers, config) {
          $scope.content = response.error;
          $scope.statuscode = response.status;
          $scope.statustext = response.statusInfo;
          console.log(response);    
       })
      .error(function (data, status, header, config) {
          $scope.ResponseDetails = "Data: " + data +
             "<hr />status: " + status +
             "<hr />headers: " + header +
             "<hr />config: " + config;
       });
});

而在服务器端,你可以得到这样的职位数据:

And in the server side you can get the post data like this:

$postdata = json_decode(file_get_contents('php://input'));
print_r($postdata);

您必须设有code在帖子正文你的数据在 urlen codeD 当请求的内容类型是应用程序/ x-WWW的形式格式-urlen coded`。这应该是这样的:

You have to encode your data in the post body in urlencoded format when the request content type is application/x-www-form-urlencoded`. Which should be like this:

var inputs = 'student_id=3';

这篇关于无法获得与AngularJS post方法正确的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆