公司的項目前端部分現在改用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)即可。
打開谷歌瀏覽器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!
