AngularJS$http使用Ajax URL发送数据


AngularJS $http sending data with Ajax URL

在使用angularjs之前,我已经使用过此代码。

function ajax_post(){
      // Create our XMLHttpRequest object
      var hr = new XMLHttpRequest();
      // Create some variables we need to send to our PHP file
      var url = "myUrl";
      var fn = document.getElementById("username").value;
      var ln = document.getElementById("password").value;
      var vars = "username="+fn+"&password="+ln;
      hr.open("POST", url, true);
      // Set content type header information for sending url encoded variables in the request
      hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      // Access the onreadystatechange event for the XMLHttpRequest object
      hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
          var return_data = hr.responseText;
        if(return_data=="1"){
          console.log("this is return data"+return_data);
        }else{
          ons.notification.alert({message: 'Login Failed!'});
        }
        }
      }
      // Send the data to PHP now... and wait for response to update the status div
      hr.send(vars); // Actually execute the request 
  }

这里与AngularJS做同样的事情

$scope.ajaxLogin = function(){
    var fn = document.getElementById("username").value;
    var pw = document.getElementById("password").value;
     $http({
    url: "myURL", 
    method: "POST",
    data: { username: fn, password: pw },
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data, status, headers, config) {
   // this callback will be called asynchronously
   // when the response is available
    if(status == 200) {
      var return_data = data;
    if(return_data == 0){
          console.log("test "+data,status);
          $scope.showAlertSucess();
        }else{
          $scope.showAlertError();
        }
      }
    }).
  error(function(data, status, headers, config) {
   // called asynchronously if an error occurs
   // or server returns response with an error status.
   $scope.showAlertNetwork();
    });
  };

但AngularJS的方式没有给出预期的输出,即"1",它给出了"0"。我浏览了webconsole,我得到的是这部分不同,我认为它发送的数据像JSONdata: { username: fn, password: pw },
但我的其他代码不是那样的var vars = "username="+fn+"&password="+ln;

如何修复它以与angularJS一起使用。

在这里了解我的PHP代码。

if ($result=mysqli_query($con,$sql))
  {
  $rowcount=mysqli_num_rows($result);
  printf($rowcount);
  mysqli_free_result($result);
  }

如果您使用AngularJs在PHP中提供变量,请使用以下代码

$array = json_decode(file_get_contents('php://input'));

$array中输入变量。