繁体   English   中英

来自 angular 的 $http.post 到达 php,但在 angularjs 中未收到响应

[英]$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM