Ajax 上的解析器错误

Parser error on Ajax

我正在尝试确认对数据库的插入,如果成功,return Json,如果失败,则捕获错误并发送异常消息。

PHP 将信息插入数据库,但由于某些原因 javascript 即使数据插入正确,return 也会出错。

在插入信息时的响应文本中,我收到一个 NULL 值 =“” 但是当它失败时 ib 插入它工作正常并捕获错误。 并且总是收到此错误:"Error. Parsing JSON Request failed."

这里是 PHP:

<?php
//Cargar coneccion a BD:
  require_once '../db/db_config.php';
//Validacion de Datos:
if (is_ajax()) {
  if (isset($_POST["param1"]) && !empty($_POST["param1"])) { //verificar si param1 existe y tiene valor
    $tipo = $_POST["param1"];    
          if (isset($_POST["param2"]) && !empty($_POST["param2"])) { //verificar si param2 existe y tiene valor
        $lista = $_POST["param2"];

        insertarUsr($tipo,$handler,$lista);
    }
  }
}
//Funcion para verifica si el request  en un tipo Ajax rquest
function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function insertarUsr($tipo, $h, $lista){
    $nomre      =$lista[0];
    $apellido   =$lista[1];
    $email      =$lista[2]; 
    $password   =$lista[3];
 try {
    $sql = "CALL proc_create_user(:tipo, :nomre, :apellido, :email, :password)";
        $handler = $h;
         $stm = $handler->prepare($sql); // preparar statments
         $stm->bindParam(':tipo', $tipo, PDO::PARAM_INT);
         $stm->bindParam(':nomre', $nomre, PDO::PARAM_STR, 4000);
         $stm->bindParam(':apellido', $apellido, PDO::PARAM_STR, 4000);
         $stm->bindParam(':email', $email, PDO::PARAM_STR, 4000);
         $stm->bindParam(':password', $password, PDO::PARAM_STR, 4000);
         if($stm -> execute()){     
                    header('Content-type: application/json');
                     echo json_encode(array(
                        'Status' => 'Success'
                        ));}

    } catch (Exception $e) {
        //echo "Error occurred:" . $pe->getMessage();
       die( "Ocurrio un Error:" . "'".(string)$e->getMessage()."'");
    }
}

?>

这是JS

function addNewUsr(tipo, arreglo){
 var datos = {param1: tipo, param2: arreglo};

 $.ajax({
      url: "resources/includes/control/create_user.php",
      type: "POST",
      data: datos,
      contentType: "application/x-www-form-urlencoded; charset=UTF-8",
      dataType: "json",
      error:function(x,e){
            if(x.status==0){
                alert('You are offline!!\n Please Check Your Network.');
            }else if(x.status==404){
                alert('Requested URL not found.');
            }else if(x.status==500){
                alert('Internel Server Error.');
            }else if(e=='parsererror'){
                alert('Error.\nParsing JSON Request failed.');
                console.log(e);
                console.log(x);
            }else if(e=='timeout'){
                alert('Request Time out.');
            }else {
                alert('Unknow Error.\n'+x.responseText);
            }
        }
      }).done(function(data, textStatus, jqXHR) {
           alert('Yey it worked!!')
          clearChildren(document.getElementById('frmUser'));
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            jqXHR.errorThrown = errorThrown;
            var message = jqXHR.responseText
            message = message.replace("Error occurred:'SQLSTATE[45000]: <<Unknown error>>", 'Error')
            alert('Ocurrio un Error\n\n'+message);
        })
        .always(function() {
        }); 

  return 1;

}

编辑:这是Headers我从google Crhome Dev Tools:

看到的
Remote Address:XXX.XXX.XXX.XXX
Request URL:http://someserver/vek/resources/includes/control/create_user.php
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate
Accept-Language:en-US,en;q=0.8,es;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:102
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost
Origin:http://someserver
Pragma:no-cache
Referer:http://someserver/vek/keyuser.php
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
param1:2
param2[]:asd
param2[]:f
param2[]:sdfsdfeagv@somemail.com
param2[]:sdfvdzfv_sfd
Response Headersview source
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html
Date:Fri, 09 Jan 2015 23:09:41 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.4 (Win64) PHP/5.4.12
X-Powered-By:PHP/5.4.12

我可以通过将 header 放在 PHP 文件的顶部来解决这个问题:

<?php
header('Content-type: application/json');
//
// rest of the code...

这返回了查询结果并回显了正确格式的 Json