[英]$http.post from angular reaches php, but response is not received back in angularjs
我遇到了一個奇怪的問題,您已經做了數千次但這次不起作用。 我已經用了兩天了,無法修復它。
所以我的代碼很簡單:
js:
$http.post('datas/test.php', data)
.success(function(response)
console.log(response);
})
.error(function() {
console.log("error");
});
測試.php:
<?php
$user=json_decode(file_get_contents('php://input'));
echo json_encode($user);
?>
當我在 $http.post 之前執行 console.log(data) 時,它包含一個具有兩個字段的對象,這兩個字段都是字符串,但是 console.log(response) 給我一個 null 所以每次我嘗試訪問像 $ 這樣的變量時用戶-> 它給了我一個錯誤。
我還有一個很奇怪的問題:當我運行我的應用程序並調用 $http.post 時,它給了我我之前說過的所有錯誤,但是如果我再試一次,$http.post 將不會出現在我重新啟動服務器之前根本不調用(它給了我一個壞網關)。
我測試了很多東西,比如改變我調用文件的方式:
$http({
method: 'POST',
url: 'datas/test.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'} // Or 'application/json'
});
但這給了我完全相同的行為。
預先感謝您幫助我,祝您有美好的一天! ;)
PS:我正在使用 PHPStorm,以防它與服務器重啟有關。
如果您使用內容類型“application/x-www-form-urlencoded”,您應該以 urlencoded 格式(即“var1=val1&var2=val2”)傳遞數據。
否則,如果您使用“application/json”,您可以直接傳遞您的 javascript 對象。
如果我能更好地幫助你,請告訴我。
再見
對於第一種方法
要以正確的方式使用 angular $http.post,您應該使用 .then 方法而不是成功方法正確處理 promise。
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
請檢查角度文檔以使用 $http.post
對於第二種方法
看起來數據沒有正確轉換。 默認情況下,$http 服務將通過將數據序列化為 JSON,然后使用內容類型“application/json”發布它來轉換傳出請求。 但是您想將值作為 FORM 帖子發布,因此您需要更改序列化算法並使用內容類型“application/x-www-form-urlencoded”發布數據。
以下來自此鏈接的代碼參考
var request = $http({
method: "post",
url: "datas/test.php",
transformRequest: transformRequestAsFormPost,
data: {
id: 4,
name: "Test",
status: "Something"
}
});
// Store the data-dump of the FORM scope.
request.success(
function( html ) {
$scope.cfdump = html;
}
);
和 TransformRequestAsFormPost 實現
app.factory(
"transformRequestAsFormPost",
function() {
// I prepare the request data for the form post.
function transformRequest( data, getHeaders ) {
var headers = getHeaders();
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
return( serializeData( data ) );
}
// Return the factory value.
return( transformRequest );
// ---
// PRVIATE METHODS.
// ---
// I serialize the given Object into a key-value pair string. This
// method expects an object and will default to the toString() method.
// --
// NOTE: This is an atered version of the jQuery.param() method which
// will serialize a data collection for Form posting.
// --
// https://github.com/jquery/jquery/blob/master/src/serialize.js#L45
function serializeData( data ) {
// If this is not an object, defer to native stringification.
if ( ! angular.isObject( data ) ) {
return( ( data == null ) ? "" : data.toString() );
}
var buffer = [];
// Serialize each key in the object.
for ( var name in data ) {
if ( ! data.hasOwnProperty( name ) ) {
continue;
}
var value = data[ name ];
buffer.push(
encodeURIComponent( name ) +
"=" +
encodeURIComponent( ( value == null ) ? "" : value )
);
}
// Serialize the buffer and clean it up for transportation.
var source = buffer
.join( "&" )
.replace( /%20/g, "+" )
;
return( source );
}
}
);
我在這里遇到的問題來自我之前在 JS 中打開的 FileReader:
reader.readAsBinaryString($scope.file);
reader.onload = function (e) {
//stuff
};
readAsBinaryString 函數使 file_get_contents("php://input") 無法正常工作。
一旦被替換為
reader.readAsDataURL($scope.file);
一切正常。
感謝 Giulio 幫助我解決這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.