Php 我是否用这个json_encode()正确处理了错误?

Php 我是否用这个json_encode()正确处理了错误?,php,jquery,json,Php,Jquery,Json,在这种情况下,我应该如何处理这两个可能的错误?我不确定这是否是推荐的方式,请有人给我建议好吗 if (isset($_GET['numberofwelds']) && isset($_GET['numberofconwelds']) { // Now we know both values definitely exist, VALIDATE them $numwelds = $_GET[

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

 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);
                 }
          }

首先需要在PHP中设置响应的内容类型。这需要在设置任何输出之前完成,否则需要使用PHP的输出缓冲区

首先使用以下内容设置标题:

header("CONTENT-TYPE: application/json");
$response = array("status" => "failure", "message" => "GET params were not numbers");

echo json_encode($response);
否则,您将需要在JavaScript中解析JSON

e、 g.$.parseJSON(jd)

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

header("CONTENT-TYPE: application/json");
$response = array("status" => "failure", "message" => "GET params were not numbers");

echo json_encode($response);
有了响应的内容类型集,现在JavaScript中就有了一个JSON对象

例如

console.log(jd.status)将输出:failure

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

(取决于生成的错误。)

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

例如

$.ajax({
  success:function(jd){
            console.log(jd.status);
          }
});
$.ajax({
      dataType:"json"
    });
记住将ajax调用的“dataType”选项设置为“json”。

例如

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

您应该对json错误响应进行编码。现在很明显,在第一个IF和最后一个ELSEOk之间缺少一个括号,所以您编辑了代码,但您使用的是哪一个代码?你至少试过了吗?那么你的问题是什么?处理两个错误是什么意思?当然,一次只会出现一个错误,就像上面所说的,您应该将这些$response编码为JSON,您不试试吗???我不是调试控制台,你知道:)