標籤:sync his param log ati php 瀏覽器 called status
公司的項目前端部分現在改用angular,一切從頭學起,今天記錄一下關於資料請求的問題,由於get的請求方式比較簡單,與post也類似,所以就單獨講講post方式。
文檔上post資料的寫法有好幾種,都是利用$http模組,通用寫法如下:
// Simple GET request example:$http({ method: ‘GET‘, url: ‘/someUrl‘}).then(function successCallback(response) { // this callback will be called asynchronously // when the response is available}, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status.});
然後我們將方式改為post,加上data試一下。
$http({ method:‘post‘, url:‘test.php‘, data:{name:‘test‘,age:20}, }).then(function successCallback(response) { alert(‘添加成功‘); }, function errorCallback(response) { alert(‘添加失敗‘);});
php檔案中我們就寫一行print_r($_POST)即可。
開啟Google瀏覽器F12,查看下調試資訊,探索資料傳輸過去了
但是細心的朋友一定會發現一個問題,就是我們這裡的傳輸方式是request playload,而不是我們通常的form data。他倆最大的區別就是,request playload的方式我們在php檔案中通過$_POST是拿不到傳過來的資料的。可以看到返回的列印資訊為空白。
我們再修改一下,加上headers和transformRequest
$http({ method:‘post‘, url:‘test.php‘, data:{name:‘test‘,age:20}, headers:{‘Content-Type‘: ‘application/x-www-form-urlencoded‘}, transformRequest: function (data) { return $.param(data); }}).then(function successCallback(response) { alert(‘添加成功‘); }, function errorCallback(response) { alert(‘添加失敗‘);});
然後查看傳回值
成功了,並且此時傳輸方式變成了
OK,over!
angular.js的post資料方式