2013-03-29 16:36

使用Angular.js的HTTP POST

  • http-post
  • json
  • php
  • angularjs
  • javascript

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

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

function PhpCtrl($scope, $http, $templateCache) {
    $scope.method = 'POST';
    $scope.url = 'url.php';
    $scope.codeStatus = "";

    $scope.add = function() {

            method: $scope.method, 
            url: $scope.url,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},  
            cache: $templateCache
        success(function(response) {
            $scope.codeStatus =;
        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!

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享