php 使用 Angular.js 的 HTTP POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15707431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:47:26  来源:igfitidea点击:

HTTP POST using Angular.js

phpjavascriptjsonangularjshttp-post

提问by matenji

I'm new to the scene and I want to use Angular.js to make an HTTP POST request. I'm accessing PHP scripts which have parameters that are just POST variables. What gets returned from each script is a JSON string. Normally in an HTML form you can make such a request like:

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

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

Depending on your input and after you click submit, JSON data1 will return something like this: { "code" : 1 }

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

I have no access to the scripts or to the servers that hosts them.

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

I was wondering if it's possible for Angular.js to read the JSON data1, match that data1 to what they're defined in my JSON data2, and then output them to my view (<pre>data2</pre>).

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

For example, if { "code" : 1 }is retrieved, I want my JSON to output the value for code #1:

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

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

Here's my attempt:

这是我的尝试:

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

All it's posting so far to the view is "Request failed" lol, although it's processing HTTP/1.1 200. I know I still have a ways to go but I would appreciate any help. Once I figure out how to post the proper JSON data1 to the view, the next step is matching and outputting the appropriate data2. Thank you in advance!

到目前为止,它在视图中发布的所有内容都是“请求失败”,哈哈,尽管它正在处理 HTTP/1.1 200。我知道我还有很长的路要走,但我会很感激任何帮助。一旦我弄清楚如何将正确的 JSON 数据 1 发布到视图,下一步就是匹配和输出适当的数据 2。先感谢您!

回答by Yahya KACEM

Acctually the problem is in the backend with PHP you don't retrieve the posted data like usual, this worked for me:

实际上,问题出在 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;
  };
}

in the PHP file:

在 PHP 文件中:

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

Hope this help.

希望这有帮助。

回答by dGo

Rather old post... but I figure my solution might come in handy for others as well.

相当旧的帖子......但我认为我的解决方案对其他人也可能派上用场。

I did not like the

我不喜欢

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

solution... Basically because it seems against good practice (I might be wrong on this)

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

This is how I got it solved (adapted to the example above)

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

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

once this done

一旦完成

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

you can access the data you normally would in PHP

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

$data = $_POST['data'];

回答by Bruno

A possible alternative it is to use an XHR request handler to serialize the payload of the POST request.

一种可能的替代方法是使用 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);
        }
    };
}]);

Moreover, if you didn't do it before, you've also to change the default content-type header of the post request:

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

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

Recently I wrote a post on my blog, where you could find more info about this approach, and XHR request interceptor.

最近我在我的博客上写了一篇文章,您可以在其中找到有关此方法和XHR 请求拦截器的更多信息。