简体   繁体   English

角$ http.post()和php?

[英]angular $http.post() and php?

I know there are several posts on SO and on many blogs explaining how to get the JSON data that was sent to be read by php. 我知道在SO和许多博客上都有几篇文章解释了如何获取php读取的JSON数据。 Some use url-encoding, others file_get_contents. 一些使用url编码,其他使用file_get_contents。

Anyway, it doesn't work for me. 无论如何,它对我不起作用。 I'm sure there is ridiculously easy explanation for it but my code simply doesn't work (the request is sent, the backend answers but that message is more or less always the same: nothing seems to arrive there ! 我敢肯定有一个非常简单的解释,但是我的代码根本不起作用(请求已发送,后端回答,但该消息或多或少总是相同的:似乎什么都没有到达!

So in my controller I have : 所以在我的控制器中,我有:

var request_data = {
    firstname: 'Quentin',
    lastname: 'Hapsburg'
  };

$http.post("lib/api/public/blog/post", JSON.stringify(request_data))
    .success(function(data) {
        console.log(data);
    })

And in the php file: 并在php文件中:

$data = file_get_contents("php://input");
$data = json_decode($data, TRUE);

var_dump($data);

The result is NULL ! 结果为NULL Any suggestions on where my error is ??? 关于我的错误在哪里的任何建议?

EDIT: This might have something to do with the rewriting rules but is not a duplicate since the same answer does not solve this question ! 编辑:这可能与重写规则有关,但不是重复的,因为相同的答案不能解决这个问题!

try using application/x-www-form-urlencoded 尝试使用application / x-www-form-urlencoded

$http.post(urlBase, $httpParamSerializer(object), {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
}).then(function(r) {
    callback(r);
});

and then php will be able to access to your posted object using $_POST 然后php将能够使用$ _POST访问您发布的对象

Please use this js file. 请使用此js文件。 It will work 会工作的

Index.html: Index.html:

<html>
<head>
   <script src="js/angular.min.js"></script>
</head>

<body ng-app="myApp">
<div ng-controller="mainCtrl">
    sdadasdasd
</div>
<script src="app.js"></script>
</body>
</html>

app.js: app.js:

var app = angular.module("myApp", []);
app.controller("mainCtrl", function($scope,$http){
    var request_data = {
        firstname: 'Quentin',
        lastname: 'Hapsburg'
    };

    $http.post("test.php", JSON.stringify(request_data)).success(function(data) {
        console.log(data);
    });
});

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

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