php - 使用 Angular.js 的 HTTP POST

标签 php javascript json angularjs http-post

我是新手,我想使用 Angular.js 发出 HTTP POST 请求。我正在访问具有只是 POST 变量参数的 PHP 脚本。从每个脚本返回的是一个 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 data1,将该 data1 与它们在我的 JSON data2 中定义的内容相匹配,然后将它们输出到我的 View ( <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,但到目前为止它向 View 发布的所有内容都是“请求失败”哈哈。我知道我还有很长的路要走,但我将不胜感激任何帮助。一旦我弄清楚如何将正确的 JSON data1 发布到 View ,下一步就是匹配并输出适当的 data2。提前致谢!

最佳答案

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

希望这对您有所帮助。

关于php - 使用 Angular.js 的 HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15707431/

相关文章:

javascript - d3.js 过滤嵌套数据中的空值

javascript - 如何动态地从对象中提取所有元素

java - 如何在javascript中将自定义对象的arraylist转换为json

php - 如何在 Apache 中同时重写和设置 header

php - 通过依赖注入(inject)传递静态类

javascript - 如何将单个 html 表单发送到 OneSignal 服务器和另一个服务器

php - Ajax "parsererror", "No conversion from text to application/json"

javascript - Firestore 返回的权限不足,即使不应该

javascript - 将文本区域内容移动到输入字段并返回会删除新行。如何克服?

c# - Java 的 "org.json"与 C#'s "Newtonsoft.Json.JsonConvert"