我是否使用此json_encode()正确处理了错误?

时间:2014-02-19 09:56:33

标签: php jquery json

在这种情况下,我该如何处理两个可能的错误?我不确定这是否是推荐的方式,请有人建议吗?

 if (isset($_GET['numberofwelds']) && isset($_GET['numberofconwelds']) 
            {
                // Now we know both values definitely exist, VALIDATE them
                $numwelds = $_GET['numberofwelds'];
                $numconwelds = $_GET['numberofconwelds'];

                if (is_int($numwelds) && is_int($numconwelds))
                {
                    // Calculate your total
                    $total = $numwelds + $numconwelds;
                    echo json_encode($total);
                }
                else
                {
                    $response = array("status" => "failure", "message" => "GET params were not numbers");
                    echo json_encode($response);
                    }

            else
            {
                 $response = array("status" => "failure", "message" => "GET params do not exist");
                 echo json_encode($response);
                 }
          }

1 个答案:

答案 0 :(得分:1)

首先需要在PHP中为响应设置CONTENT-TYPE。这需要在设置任何输出之前完成,否则您将需要使用PHP的输出缓冲区。

首先使用此设置标题:

header("CONTENT-TYPE: application/json");

否则,您需要在JavaScript中解析JSON。

e.g。 $ .parseJSON(JD);

其次,如果要返回响应数组的JSON数据,可以执行以下操作:

$response = array("status" => "failure", "message" => "GET params were not numbers");

echo json_encode($response);

通过设置响应的CONTENT-TYPE,您将在JavaScript中拥有一个JSON对象。

例如

console.log(jd.status)将输出:失败

console.log(jd.message)将输出:GET参数不是数字

(取决于生成的错误。)

请记住,这些错误并不能取代jQuery的AJAX错误。这些将在成功方法中返回。所以你会在那里处理它们。

<强> E.g

$.ajax({
  success:function(jd){
            console.log(jd.status);
          }
});

请记住为ajax调用“json”设置“dataType”选项。

<强> E.g

$.ajax({
      dataType:"json"
    });