2016-02-26 55 views
-1

我只是想知道是否有一种方法可以在使用json_decode回显响应时绕过所有PHP消息。用AngularJS忽略PHP消息

我目前的问题是,如果我的PHP代码有任何回声或其他任何包含在输出中的数组除外,我的Javascript根本无法工作。

PHP:

<?php 
error_reporting(1); 
$errors = array(); 
$data = []; 
// data from angular to be handled and 
// then if all goes well set submission to true to display with ng-show 
$data["submission"] = true; 
header('Content-Type:application/json;'); 
echo json_encode($data); 
?> 

JS:

$scope.testProcessForm = function() { 
     $http({ 
     method : 'POST', 
     url  : 'reg.php', 
     data : $scope.formData, 
     headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
    }) 
     .then(function(response) { 
     console.log(response); 
     $scope.submission = response.data.submission; 

     }, function(error) { 
      console.log('error', error); 

我认为通过使用response.data.submission我可以只访问里面有,但如上所提到的数据如果包含任何不在数组中的PHP输出,代码会中断。

是否有可能只是访问/响应$ data数组,以便它不会中断?

+0

你应该使用'error_log',而不是'echo'打印出调试信息/错误。使用'error_log'会把消息放到'php_error_logs'文件中。 –

+0

如何不在PHP中输出任何多余的消息,并确保您输出实际有效的JSON ...! – deceze

回答

1

可以调用前用ob_cleanhttp://php.net/manual/en/function.ob-clean.php)输出最后的回声:

<?php 
error_reporting(1); 
// you also need to add ob_start() 
ob_start(); 
$errors = array(); 
$data = []; 
// data from angular to be handled and 
// then if all goes well set submission to true to display with ng-show 
$data["submission"] = true; 
header('Content-Type:application/json;'); 
ob_clean(); 
echo json_encode($data); 
?> 
+0

太棒了,正是我需要的,谢谢! – HenrikM

1

error_reporting();应设置为0 =>error_reporting(0);

还要注意的是所有可能的条件,可能会导致错误应该语法处理,您可以发送错误代码(使用http_response_code(404/500))以及可以在客户端读取的响应。

1
error_reporting(0); 

而不是

error_reporting(1); 
+0

它仍然显示我的回声从我的PHP代码:(这是否意味着我必须删除所有的回声? – HenrikM

+0

啊对不起 - 我误解了,并认为你只是想压制错误,我可能会建议避免回声的东西。 _need_以这种方式呈现输出,可以考虑启动一个名为'$ output'或类似的变量,并将输出附加到它'$ output。='你的东西';'然后你可以在需要时回显它,当你不需要时弹出不需要它。 – Bat