angularjs $http提交數據探索


前兩天在搞自己的項目,前端js框架用的是angularjs框架;網站整的差不多的時候出事了;那就是當我用$http.post()方法向服務器提交一些數據的時候;后台總是接收不到數據;

於是采用了其他方法暫時性替代一下;

今天正好有時間研究這個事情;網上查了很多資料;都試了試;都是不太好;但是還是給我提供了一些解決問題的思路;

正文開始:首先做了個demo如下;主要是為了比較他們的不同之處;

 

html如下:

<div class="container-fluid" data-ng-app="jjd" data-ng-controller="index">
	<div class="container">
		<div class="row">
			
			<div class="col-md-5">
				<p class="h4 text-center">jQ的$.post()提交</p>
				<p> </p>
				<div class="form-group">
					<label for="exampleInputEmail1">用戶名</label>
					<input type="text" ng-model="sdata.name" class="form-control" placeholder="用戶名">
				</div>
				<div class="form-group">
					<label for="">密碼</label>
					<input type="password" ng-model="sdata.pwd" class="form-control" placeholder="密碼">
				</div>
				<button type="button" class="btn btn-primary btn-block" ng-click="jPostData()">jQ提交</button>
			</div>
			<div class="col-md-2"> </div>
			<div class="col-md-5">
				<p class="h4 text-center">angularjs的$http.post()功能</p>
				<p> </p>
				<div class="form-group">
					<label for="exampleInputEmail1">用戶名</label>
					<input type="text" ng-model="sdata2.name" class="form-control" placeholder="用戶名">
				</div>
				<div class="form-group">
					<label for="">密碼</label>
					<input type="password" ng-model="sdata2.pwd" class="form-control" placeholder="密碼">
				</div>
				<button type="button" class="btn btn-primary btn-block" ng-click="aPostData()">$http提交</button>
			</div>
			
		</div>
	</div>
</div>

  js代碼如下:

var app = angular.module('jjd',[]);
app.controller('index',function($scope,$http){
    $scope.sdata = {
        name:'jQuery',
        pwd:'jQuery'
    };
    $scope.sdata2 = {
        name:'Angularjs',
        pwd:'Angularjs'
    };
    
    /*jQ的ajax提交*/
    $scope.jPostData = function(){
        //console.log($scope.sdata);
        $.post('/web/data.php',$scope.sdata,function(d){
            console.log(d);
        })
    };
    
    /*angularjs的$http提交*/
    $scope.aPostData = function(){
        
        $http({
            url: '/web/data.php',
            method: 'POST',
            data:$scope.sdata2
            }
        }).success(function(da){
            console.log(da);
        });
    };
});

后台采用php的$_POST接收:

<?php
header("Content-type: text/html; charset=utf-8"); 
$aname = $_POST['name'];
$apwd = $_POST['pwd'];

$msg = array();
$msg['name'] = $aname;
$msg['pwd'] = $apwd;
echo json_encode($msg);
?>

服務器采用wampsever的本地啟動的本地服務器。致此,頁面服務搭建完畢;開始測試;

結果如圖:

 

從上圖的對比中可以看出后台接收不到值得原因主要是1、2、3處不同;

其中1和2是請求的頭文件信息;

3是數據類型不同;jq發送的是Form Data;而angularjs默認發送的是json數據;

 

產生原因已經找到;下面開始改造;

首先針對1和2,在$http()的方法中配置header信息;

其次對數據進行轉換;這里我做了個簡單的json到string轉換的服務;

改造后的代碼如下:

/*------創建angularjs應用------*/
var app = angular.module('jjd',[]);

/*創建json格式到string的轉換服務*/
app.service('jsonToStr',function(){
    this.transform = function(jsonData){
        var string = '';
        
        for(str in jsonData){
            string = string + str +'=' + jsonData[str] +'&';
        }
        
        var _last = string.lastIndexOf('&');
        
        string = string.substring(0,_last);
        
        return string;
    };
});

/*---------首頁控制器--------*/
app.controller('index',function($scope,$http,jsonToStr){//注入創建的jsonToStr服務
    $scope.sdata = {
        name:'jQuery',
        pwd:'jQuery'
    };
    $scope.sdata2 = {
        name:'Angularjs',
        pwd:'Angularjs'
    };
    
    /*jQ的ajax提交*/
    $scope.jPostData = function(){
        //console.log($scope.sdata);
        $.post('/web/data.php',$scope.sdata,function(d){
            console.log(d);
        })
    };
    
    /*angularjs的$http提交*/
    $scope.aPostData = function(){
        //console.log(jsonToStr.transform($scope.sdata2));
        
        $http({
            url: '/web/data.php',
            method: 'POST',
            data:$scope.sdata2,
            data: jsonToStr.transform($scope.sdata2),//對提交的數據格式化
            headers: {
                'Accept': '*/*',
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).success(function(da){
            console.log(da);
        });
    };
});

致此,angularjs提交數據后台接收不到的問題解決(只針對json數據格式);獻給奮斗中的小伙伴;

 

這個問題應該還有一種思路;就是在服務端進行對獲取json格式的數據的支持,有興趣的小伙伴可以嘗試一下;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM