您好,登錄后才能下訂單哦!
小編給大家分享一下AngularJS中$http模塊POST請(qǐng)求的實(shí)現(xiàn)方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
一、代碼如下:
$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); //傳的數(shù)據(jù)都在$post中了;
二、 $http請(qǐng)求數(shù)據(jù)主要會(huì)有以下三種方式
1.get請(qǐng)求
2.post請(qǐng)求
3.jsonp
<!DOCTYPE html> <html lang="zh_CN"> <head> <meta charset="UTF-8"> <title>Angular基礎(chǔ)</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="angular.min.js"></script> <script type="application/javascript"> var myApp=angular.module('myApp',[]); myApp.controller('personCtrl',function($scope,$http){ $http.get('getData.php'). success(function(data) { console.log(data); }). error(function(err) { //錯(cuò)誤代碼 }); //$http.post采用postJSON方式發(fā)送數(shù)據(jù)到后臺(tái), // 解決辦法:在后臺(tái)php中使用$postData=file_get_contents("php://input",true);這樣就可以獲得前端傳送過來的數(shù)據(jù) var postData={msg:'post的內(nèi)容'}; var config={params:{id:'5',name:'張三豐'}}; $http.post('postData.php', postData,config). success(function(data) { console.log(data); }). error(function(err) { //錯(cuò)誤代碼 }); var myUrl ="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSON_CALLBACK"; $http.jsonp(myUrl).success( function(data){ console.log(data); } ).error(function(err){ //錯(cuò)誤代碼 }); $scope.firstName="Wang"; $scope.lastName="Ben"; }); </script> </body> </html>
<?php //postData.php文件 //用接收json數(shù)據(jù)的方式 $msg=file_get_contents("php://input",true); $name=$_GET['name']; echo $name.$msg."_post";
顯示效果:
以上是“AngularJS中$http模塊POST請(qǐng)求的實(shí)現(xiàn)方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。