天天看點

Angularjs POST/GET/JSONP請求

1,POST請求

POST請求應該是一般項目用的最多的請求方式,這裡的header分幾種:

application/x-www-form-urlencoded

标準的編碼格式,也是Jquery的Ajax請求預設方式,這種方式的好處就是浏覽器都支援,在請求發送過程中會對資料進行序列化處理,以鍵值對形式?key1=value1&key2=value2的方式發送到伺服器,如果用Jquery,它内部已經進行了處理,如果自己寫原生的Ajax請求,就需要自己對資料進行序列化。 

需要transformRequest。

transformRequest為函數或者函數數組,用來對http請求的請求體和頭資訊進行轉換,并傳回轉換後的結果。

$http({
            method:"POST",
            url:basePath+"/faInvestor/closeFAInvestor",
            data:{"investorId":Number(data),"isClose":Number(id)},
            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("&");
            }
        }).then(function succses(response) {

            console.log("success")
            console.log(data+","+id)
            console.log(response)
            
        },function (response) {
            console.log("error")
            console.log(data+","+id)
            console.log(response)
        })
    }
           

application/json

告訴伺服器請求的主題内容是json格式的字元串,伺服器端會對json字元串進行解析,這種方式的好處就是前端人員不需要關心資料結構的複雜度,隻要是标準的json格式就能送出成功。

不需要transformRequest。

這裡是先把資料封裝成對象,然後使用 angular.toJson()轉化為json資料。

$scope.jsonBody={
            industryList:$scope.middleIndustryList,
            areaAList:$scope.middleCountryId,
            stageList:$scope.middleStageId,
            financingList:$scope.middleFinancingId,
            financingOutList:$scope.middlefinancingOutList,
            minRMBAmount:$scope.middleMinRMBAmount,
            maxRMBAmount:$scope.middleMaxRMBAmount,
            status:$scope.middleStatus,
            leaderId:'',
            currentPage:Number(page),
            pageSize:10,
        }
           
$http({
            method:"POST",
            url:basePath+"/faInvestor/getFAInvestorList",
            data:angular.toJson($scope.jsonBody),
            headers:{'Content-Type': 'application/json;charset=UTF-8'}
        }).then(function (response) {
            console.log($scope.jsonBody)
            console.log(response.data)
           
        },function (response) {
            console.log("error")
            console.log($scope.jsonBody)
        })
    }
           

undefined

用于檔案上傳,angular對于post和get請求預設的Content-Type是application/json。通過設定‘Content-Type’: undefined,這樣浏覽器不僅幫我們把Content-Type 設定為 multipart/form-data,還填充上目前的boundary,如果你手動設定為: ‘Content-Type’: multipart/form-data,背景會抛出異常:the current request boundary parameter is null。 通過設定 transformRequest: angular.identity ,anjularjs transformRequest function 将序列化我們的formdata object.

angular.identity :函數傳回本身的第一個參數。這個函數一般用于函數風格。

(可以将對象轉成json資料,然後通過.append追加到form對象裡,上傳檔案的同時,送出資料)

var form = new FormData();
        var business = document.getElementById("business").files[0];
        var finance = document.getElementById("finance").files[0];
        var others = document.getElementById("others").files[0];
        form.append('businessFile',business);
        form.append('financingFile',finance);
        form.append('otherFile',others);
        form.append('jsonStr',angular.toJson(infoData));
        form.append('optType',1);
        console.log(form);
        $http({
            method: 'POST',
            url: basePath+"/project/saveOrUpdateFAProject",
            data: form,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        }).then(function success(response) {  
            console.log(infoData)
            console.log(response.status)
            console.log(' upload success');  
        },function(response){   
            console.log(infoData)
            console.log(response)
            console.log(' upload fail');
      
        })
           

2,GET請求

通過url發送請求:

可直接将參數追加到url裡,無需設定headers。

$http({
                method:"GET",
                url:basePath+"/area/getAreaByParentId?parentId="+$scope.countryId
            }).then(function succese(response) {
                console.log(response.data)
            })
           

3,JSONP請求

用于解決跨域的問題。

1,請求格式為XMLHttpRequest

2,ip或端口不一緻

滿足以上兩點就會出現跨域問題,JSONP就是通過解決了請求格式,進而解決了跨域問題。

JSONP跨域請求的url後一定要追加參數callback,并且callback的值是固定的,即JSON_CALLBACK

$http({ 
    method: 'JSONP', 
    url: 'http://www.b.com/test.php?callback=JSON_CALLBACK' 
}).then(
           
function(response){ 
    console.log(response); 
})
           

java服務端也需要加入跨域允許腳本:

response.setHeader("Access-Control-Allow-Origin", "*");  
response.setHeader("Access-Control-Allow-Methods","POST");  
response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");  
response.setContentType("text/html;charset=utf-8");  
response.setCharacterEncoding("utf-8");  
request.setCharacterEncoding("utf-8"); 
           

繼續閱讀