使用Angular.js的HTTP POST

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:

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

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>).

For example, if { "code" : 1 } is retrieved, I want my JSON to output the value for code #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!

dra8603
dra8603 嗨,克里斯,感谢您的评论和建议!关于$scope的模型绑定是有意义的,所以我会记得使用局部变量。我已经玩过JS调试器了,但是由于我在本地测试,它一直在抛出有关相同原始策略的错误,因此我暂时使用Firefox。
7 年多之前 回复
douyin7829
douyin7829 2件事:1)您不应该在$scope上设置这些值,$scope用于模型绑定,并且其上的所有值都是Watched,并且它们的值应用于具有性能影响的同名字段。只需将它们设置为局部变量,如varmethod='POST',它们将在http函数中用作Closure的一部分。2)你知道如何进入Chrome/Firefox中的JS调试器吗?用它来检查响应。在Chrome右上角>开发人员工具中,如果添加调试器,则需要“网络”选项卡和“控制台”;线路到错误功能。
7 年多之前 回复
doupu1957
doupu1957 感谢您的答复。我不确定我是否正确这样做,但是我只是将FormData中的表单数据包装为'JSON对象'吗?我试过这个pastebin.com/QMZSr4AZ并且它仍在处理'请求失败'错误,所以我猜我仍然无法发送数据。
7 年多之前 回复
dongyoucha0645
dongyoucha0645 也许请求失败是因为你做了一个post请求而没有用它发送数据,尝试将所有表单字段放在FormData对象中并通过添加这些数据发送请求:FormData作为参数放入$http请求后其中的所有表单字段或标题都不正确。希望这有帮助。
7 年多之前 回复

3个回答

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

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:

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

Hope this help.

doufei2194
doufei2194 这是一个巨大的帮助! 非常感谢@YahyaKACEM。 干杯!
5 年多之前 回复
douxie5930
douxie5930 parse_str(file_get_contents('php:// input'),$ data); 使用PHP 5.3.13为我工作。
大约 6 年之前 回复
dongwen9975
dongwen9975 我的PHP版本是PHP 5.5.3,这对我来说很好#ta7yaISI#Ta7yaTounes
接近 7 年之前 回复
doz59484
doz59484 这在php 5.3.13中不起作用
接近 7 年之前 回复
douhao2026
douhao2026 不,这只是一个例子,在此之前的那一行是您需要进行数据处理然后回显所需的返回消息之后所需的行。
7 年多之前 回复
dozabg1616
dozabg1616 Yahya,开发人员尝试实现该脚本,但它说它无法从非对象获取属性“名称”。 是否必须使用行(echo $ data-> name;)?
7 年多之前 回复

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

$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:

$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.



相当古老的帖子......但我认为我的解决方案也可以为其他人派上用场。</ p>

我不喜欢</ p>

  json_decode(file_get_contents(“php:// input”)); 
</ code> </ pre>

解决方案...基本上因为它似乎违反了良好的做法(我可能在这方面做错了)</ p>

这就是我解决它的方法(适用于上面的例子)</ p >

  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;
})。
错误 (本功能 离子(响应){
$ scope.codeStatus = response || “请求失败”;
});
返回false;
};
}
</ code> </ pre>

完成后</ p>

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

您可以访问PHP中通常的数据</ p>

  $ data = $ _POST ['data']; 
</ 代码> </ pre>
</ div>

展开原文

原文

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

$data = $_POST['data'];

dongtanhe4607
dongtanhe4607 很好的解决方案,但PUT,DELETE和OPTIONS需要像@Yahya KACEM那样从PHP方面说
接近 2 年之前 回复
duanmei2459
duanmei2459 以下是param函数的独立函数:var param = function(data){var returnString =''; for(var d in data){if(data.hasOwnProperty(d)){returnString + = d +'='+ data [d] +'&'; return returnString.slice(0,returnString.length - 1); };
大约 4 年之前 回复
dongluanguang4774
dongluanguang4774 是的...抱歉...应该提到这使用了jQuery的$ .params()函数
4 年多之前 回复
dongzhan8620
dongzhan8620 好吧,好像你需要jQuery才能工作。 否则$ .param未定义。
4 年多之前 回复
duanci6484
duanci6484 绝对不行。 $未定义
4 年多之前 回复
dongxiong5546
dongxiong5546 我不知道在回答这个问题时是否有任何改变,但$ .param()对我来说是未定义的,我工作的是使用:$ httpParamSerializerJQLike(FormData)
4 年多之前 回复
dongtao9887
dongtao9887 请求数据中是否真的需要$ templateCache?
大约 6 年之前 回复
doujia7517
doujia7517 好的解决方案
大约 6 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐