【问题标题】:Ignoring PHP messages with AngularJS使用 AngularJS 忽略 PHP 消息
【发布时间】:2016-02-26 10:00:58
【问题描述】:

我只是想知道在使用 json_decode 回显响应时是否有办法绕过所有 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 数组以使其不会损坏?

【问题讨论】:

  • 您应该使用error_log 而不是echo 来打印调试信息/错误。使用error_log 会将消息放入您的php_error_logs 文件中。
  • 不要在 PHP 中输​​出任何多余的消息并确保输出实际有效的 JSON...!?

标签: javascript php angularjs


【解决方案1】:

您可以在调用最后一个回显之前使用ob_clean (http://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);
?>

【讨论】:

    【解决方案2】:

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

    还请注意,所有可能导致错误的情况都应以语法方式处理,您可以发送错误代码(使用http_response_code(404/500))以及可以在客户端读取的响应。 p>

    【讨论】:

      【解决方案3】:
      error_reporting(0);
      

      而不是

      error_reporting(1);
      

      【讨论】:

      • 它仍然显示我的 PHP 代码中的回声 :( 这是否意味着我必须删除所有回声?
      • 啊抱歉 - 我误解了,还以为你只是想抑制错误。我可能会建议避免重复的事情。如果您需要以这种方式呈现输出,请考虑启动一个名为$output 或类似名称的变量并将输出附加到它$output .= 'your stuff'; 然后您可以在需要时回显它,而不会在您不使用时弹出它不想要。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      相关资源
      最近更新 更多