【问题标题】:AngularJS $http.post and PHPAngularJS $http.post 和 PHP
【发布时间】:2014-07-04 12:14:29
【问题描述】:

我正在使用 AngularJS 来 $http.post 一个对象,但我还想在 URL 中包含某种数据(或其他方式)以指定该对象包含的内容以及在 PHP 文件中解析它的位置.知道如何将类似于 GET 的变量发送到 AngularJS 帖子中,以便在 PHP 中将对象路由到正确的 if 语句进行解析吗?

这是我的 AngularJS 代码:

$scope.saveSchool=function(){
  var schoolData = angular.copy($scope.schoolsModal);
  $http.post('data/data.php?schoolModal=save', schoolData).error(function(){
    console.log('Did not post data to data.php');
  });
};

这是我在 data.php 文件中的 PHP 代码,希望接收对象并将其路由到正确的 if 语句以解析并最终保存数据。

if (isset($_GET["schoolModal"])) {
  if ($_GET["schoolModal"] == "save") {
   $postdata = file_get_contents("php://input");
   $request = json_decode($postdata);
   echo "Acknowledged";
   echo $postdata;
 }

}

这不起作用,因为它不会抛出任何错误或返回任何东西 (PHP)。这确实有效,但我无法在 php 文件中路由对象(我必须为这个 angularjs json 对象创建一个单独的 php 文件)。

$scope.saveSchool=function(){
  console.log('saveSchool function initiated');
  var schoolData = angular.copy($scope.schoolsModal);
  $http.post('data/data.php', schoolData).error(function(){
    console.log('Did not post data to data.php');
  });
};

需要在自己的文件中的 PHP 脚本,因为我希望最终拥有多个 post 函数并在收到数据时对其进行解析:

if($_SERVER['REQUEST_METHOD']=='POST'){
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo $postdata;

}

那个 PHP 代码工作得很好,但我无法将数据路由到它需要去的地方。我不想将所有帖子发送到该 if 语句。任何想法,我都是 AngularJS 和 PHP 的新手,并尽我所能去学习。

【问题讨论】:

  • 我正在尝试找到一种方法来标记传入的帖子信息,以便我知道在 PHP 中如何处理它。
  • 一般来说,我认为你需要设置 HTTP 主机头。你见过这个吗? victorblog.com/2012/12/20/…

标签: javascript php json angularjs post


【解决方案1】:

考虑一下我做的一个项目中的这个例子。它只有 1 个参数“状态”,但显然您可以将所有参数添加到这样的对象中

postFavorite: function(id, type, record, resource) {
  var xsrf = $.param({status: record.prop});

  $http({
    method: 'POST',
    url: this.api_base + '/favorites/'+type+'/'+id,
    data: xsrf,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},                 
    withCredentials: true
  }).success(function(data, status, headers, config){
    if(data.success){
      console.log("Success:", data, status, headers, config);
    }
  });
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多