javascript - AngularJS $http.post 和 PHP

标签 javascript php json angularjs post

我正在使用 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 的新手,并尽我所能接受它。

最佳答案

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

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

关于javascript - AngularJS $http.post 和 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23688561/

相关文章:

javascript - 从 onclick 调用时 $.ajax 不工作

javascript - EPUB3 输入数据并将它们保存在某处

r - 将json对象转换为空间线数据框

c# - Dotnet webclient 超时,但浏览器可以处理 json web 服务的文件

Python:为什么数据被插入到列表/字典的两个字典中

javascript - 无法将变量传递给ajax url

javascript - 将组件的状态传递给 mapDispatchToProps React/Redux

php - PHP-FPM 的多个版本,安装和配置...?

php - 从 laravel 中的数据库或模型返回格式化时间

php - Kohana 准备好的语句或查询构建?