我尝试确认插入到数据库并在成功时返回Json,如果失败则捕获错误并发送异常消息。
PHP将信息插入到数据库中,但由于某种原因,即使正确插入数据,javascript也会返回错误。
在插入信息的响应文本中,我收到一个NULL值="" 但是当它失败时ib插入它工作正常并捕获错误。 并始终收到此错误:"错误。解析JSON请求失败。"
这是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;
}
修改:这是我从谷歌Crhome开发工具中看到的标题:
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
答案 0 :(得分:1)
我能够通过将标题放在PHP文件的顶部来解决这个问题:
<?php
header('Content-type: application/json');
//
// rest of the code...
这返回了查询结果并回显了格式正确的Json