AngularJS $http模块POST请求实现

(编辑:jimmy 日期: 2024/9/30 浏览:2)

一、代码如下:

$http({ 


  method:'post', 

  url:'post.php', 

  data:{name:"aaa",id:1,age:20} 

}).success(function(req){ 

  console.log(req); 

}) 

解决方案:

1、 

var myApp = angular.module('app',[]);

myApp.config(function($httpProvider){

 

$httpProvider.defaults.transformRequest = function(obj){

var str = [];

for(var p in obj){

str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));

}

return str.join("&");

  2.  

$http({

method:'post',

url:'post.php',

data:{name:"aaa",id:1,age:20},

headers:{'Content-Type': 'application/x-www-form-urlencoded'},

transformRequest: function(obj) {

var str = [];

for(var p in obj){

str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));

}

return str.join("&");

}

}).success(function(req){

console.log(req);

})

 php

 $rawpostdata = file_get_contents("php://input");
 $post = json_decode($rawpostdata, true);
 //传的数据都在$post中了;

二、 $http请求数据主要会有以下三种方式

1.get请求

2.post请求

3.jsonp

<!DOCTYPE html>
<html lang="zh_CN">
<head>
  <meta charset="UTF-8">
  <title>Angular基础</title>
</head>
<body>
<div ng-app="myApp">
  <div ng-controller="personCtrl">
    姓:<input type="text" ng-model="firstName"/><br/>
    名:<input type="text" ng-model="lastName"/><br/>
    姓名:<span ng-bind="firstName"></span><span ng-bind="lastName"></span>
  </div>

</div>
<script src="/UploadFiles/2021-04-02/angular.min.js">


<"php://input",true);

$name=$_GET['name'];
echo $name.$msg."_post";

显示效果:

AngularJS $http模块POST请求实现

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。