2014-08-29 46 views
1

請告訴我的代碼做我用這個功能

jQuery.ajax({ 
     type: 'POST', 
     url: urlSubmit, 
     timeout: 5000, 
     dataType: 'text', 
     data: { 
      date : dataDate, 
      url : dataUrl, 
      domaine : dataDomaine, 
      email : dataEmail, 
      destinataire : dataDestinataire, 
      msg : dataMsg 
     }, 
     "success": function (jqXHR, textStatus, errorThrown) { 
      console.log("AJAX success :) - statut " + textStatus); 
      $timeout(successMailZR_alerte, 3000); 
     }, 
     "error": function (jqXHR, textStatus, errorThrown) { 
      console.log("AJAX fail :/ - statut " + textStatus); 
      $timeout(errorMailZR_alerte, 3000); 
     } 

    }); 

:POST代碼的PHP腳本誰發送電子郵件。

但是,因爲我rewrited我的代碼在一個完整的angularjs應用程序,我不喜歡這樣寫道:

$http({ 
     method: 'POST', 
     url: urlSubmit, 
     timeout: 5000, 
     cache: false, 
     data: { 
      date : dataDate, 
      url : dataUrl, 
      domaine : dataDomaine, 
      email : dataEmail, 
      destinataire : dataDestinataire, 
      msg : dataMsg 
     }, 
     headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
     responseType: 'text', 
    }). 
    success(function(data, status, headers, config) { 
     console.log("AJAX success :) - statut " + status); 
     $timeout(successMailZR_alerte, 3000); 
    }). 
    error(function(data, status, headers, config) { 
     console.log("AJAX fail :/ - statut " + status); 
     $timeout(errorMailZR_alerte, 3000); 
    }); 

問題是:以$ HTTP,我有一個成功的200,但沒有張貼,我沒有返回我的電子郵件。有什麼問題 ?

+0

那麼,下載Fiddler2並比較傳出的請求,你錯過了什麼?設置它。 – 2014-08-29 06:57:38

回答

0

要理解這一個需要了解的angularjquery設置請求頭,沒有與時請求後的jQuery像頭的差異則標題可能是這樣的:

POST /some-path HTTP/1.1 
Content-Type: application/x-www-form-urlencoded // default header set by jQuery 

foo=bar&name=John 

你可以看到如果你使用chrome,那麼你可以在網絡標籤的chrome inspector中看到這個,如果你點擊請求,你可以看到由jQuery設置的form data和內容頭。

在另一邊有角的js $http服務,當一個請求時,那麼你可以找到這些:

POST /some-path HTTP/1.1 
Content-Type: application/json // default header set by angular 


{ "foo" : "bar", "name" : "John" } 

真正的區別是你有一個request payload不常見form data它使用jQuery的。所以你需要在下面的服務器端做一些額外的事情。

使用此:

$data = json_decode(file_get_contents("php://input")); 
echo $data->date; 
// and all other params you have sent 

這是由於它的默認標題

  • 接受:應用/ JSON,純文本/,*/*
  • 內容類型:應用程序/ json

和jQuery不可能有別的東西:

  • 內容類型:應用程序/ x-WWW的形式,進行了urlencoded;字符集= UTF-8
2

的問題是,jQuery的POST併發送你的數據作爲表格數據(例如鍵 - 值對)(https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_and_retrieving_form_data),而在AngularJS請求負載發送數據。對於兩者之間的差異請參見下面的SO問題:What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

爲了使您的角度腳本與您的服務器,你有如下描述你的數據轉換爲URL編碼字符串:How can I post data as form data instead of a request payload?。僅僅設置headers: {'Content-Type': 'application/x-www-form-urlencoded'}是不夠的。

另一種方法是調整應用程序的後端以解析消息負載而不是表單數據參數。