angular.js的post資料方式

來源:互聯網
上載者:User

標籤: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資料方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.