繁体   English   中英

使用Angular.js的HTTP POST

[英]HTTP POST using Angular.js

我是新手,我想使用Angular.js发出HTTP POST请求。 我正在访问PHP脚本,其参数只是POST变量。 从每个脚本返回的是JSON字符串。 通常在HTML表单中,您可以提出如下请求:

<form method="post" action="url.php">
<input name="this">
<input name="that">
<input value="Submit">
</form>

根据您的输入,在您单击提交后,JSON data1将返回如下内容: { "code" : 1 }

我无权访问脚本或托管它们的服务器。

我想知道Angular.js是否可以读取JSON数据1,将数据1与我们在JSON数据2中定义的内容相匹配,然后将它们输出到我的视图( <pre>data2</pre> )。

例如,如果检索到{ "code" : 1 } ,我希望我的JSON输出代码#1的值:

{ "code" : [
  { 1: "User already logged in." }, 
  { 2: "Wrong parameters, try again."}, 
  { 3: "etc., etc." }
 ] 
};

这是我的尝试:

<form ng-controller="PhpCtrl" name="f1">
<input type="text" name="name">
<input type="text" name="password">
<pre ng-model="codeStatus">{{codeStatus}}</pre>
<input type="submit" ng-click="add()" value="Submit">
</form>

function PhpCtrl($scope, $http, $templateCache) {
    $scope.method = 'POST';
    $scope.url = 'url.php';
    $scope.codeStatus = "";

    $scope.add = function() {

        $http({
            method: $scope.method, 
            url: $scope.url,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},  
            cache: $templateCache
        }).
        success(function(response) {
            $scope.codeStatus = response.data;
        }).
        error(function(response) {
            $scope.codeStatus = response || "Request failed";
        });
        return false;   
    };
}

迄今为止所有它发布到视图的是“请求失败”大声笑,虽然它正在处理HTTP / 1.1 200.我知道我还有很长的路要走但我会感激任何帮助。 一旦我弄清楚如何将正确的JSON数据1发布到视图,下一步就是匹配并输出相应的数据2。 先感谢您!

实际上问题是在PHP的后端你没有像往常一样检索发布的数据,这对我有用:

function PhpCtrl($scope, $http, $templateCache) {
  var method = 'POST';
  var url = 'url.php';
  $scope.codeStatus = "";
  $scope.add = function() {
    var FormData = {
      'name' : document.f1.name.value,
      'password' : document.f1.password.value
    };
    $http({
      method: method,
      url: url,
      data: FormData,
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      cache: $templateCache
    }).
    success(function(response) {
        $scope.codeStatus = response.data;
    }).
    error(function(response) {
        $scope.codeStatus = response || "Request failed";
    });
    return false;
  };
}

在PHP文件中:

$data = json_decode(file_get_contents("php://input"));
echo $data->name;

希望这有帮助。

相当古老的帖子...但我认为我的解决方案也可能派上用场。

我不喜欢

json_decode(file_get_contents("php://input"));

解决方案...基本上因为它似乎违反了良好的做法(我可能错了)

这就是我解决它的方法(适用于上面的例子)

function PhpCtrl($scope, $http, $templateCache) {
  var method = 'POST';
  var url = 'url.php';
  $scope.codeStatus = "";
  $scope.add = function() {
    var FormData = {
      'name' : document.f1.name.value,
      'password' : document.f1.password.value
    };
    $http({
      method: method,
      url: url,
      data: $.param({'data' : FormData}),
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      cache: $templateCache
    }).
    success(function(response) {
        $scope.codeStatus = response.data;
    }).
    error(function(response) {
        $scope.codeStatus = response || "Request failed";
    });
    return false;
  };
}

一旦完成

data: $.param({'data' : FormData}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},

您可以访问PHP中通常的数据

$data = $_POST['data'];

可能的替代方案是使用XHR请求处理程序来序列化POST请求的有效负载。

$httpProvider.interceptors.push(['$q', function($q) {
    return {
        request: function(config) {
            if (config.data && typeof config.data === 'object') {
                // Check https://gist.github.com/brunoscopelliti/7492579 for a possible way to implement the serialize function.
                config.data = serialize(config.data);
            }
            return config || $q.when(config);
        }
    };
}]);

此外,如果您之前没有这样做,您还需要更改发布请求的默认内容类型标头:

$http.defaults.headers.post["Content-Type"] = 
    "application/x-www-form-urlencoded; charset=UTF-8;";

最近我在我的博客上写了一篇文章,在那里你可以找到关于这种方法的更多信息,以及XHR请求拦截器

暂无
暂无

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

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