Php Wordpress中带有JSON的Ajax解析器错误
我正在为一所学校做一个应用程序网站,当我试图编辑一个学生时,我被卡住了。我想让用户在和特定学生的行中单击,然后打开一个包含其数据的表单 我必须做一个ajax请求,这样我就可以调用我的php函数(在我的数据库上进行查询的函数)并将数据加载到表单中。这是我的ajax请求jQuery代码:Php Wordpress中带有JSON的Ajax解析器错误,php,jquery,json,ajax,wordpress,Php,Jquery,Json,Ajax,Wordpress,我正在为一所学校做一个应用程序网站,当我试图编辑一个学生时,我被卡住了。我想让用户在和特定学生的行中单击,然后打开一个包含其数据的表单 我必须做一个ajax请求,这样我就可以调用我的php函数(在我的数据库上进行查询的函数)并将数据加载到表单中。这是我的ajax请求jQuery代码: //When you click in the table students, in some element whose class is edit ... $("#tblAlumnos").on("cl
//When you click in the table students, in some element whose class is edit ...
$("#tblAlumnos").on("click", ".editar", function(event) {
var rowID = $(this).parents('tr').attr('id');
$.ajax({
type: 'POST',
url: '../ajax/',
data: {'table': 'alumnos', 'action': 'carga', 'ids': rowID},
dataType: 'json',
success: function(result) {
console.log(result.nombre);
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
alert(jqXHR.status);
alert(jqXHR);
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
ajax请求调用从my db获取数据的方法:
function cargaAlumno($ids) {
require 'db.php';
$sql = "SELECT * FROM Alumnos WHERE ID=$ids";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
$row = $result -> fetch_assoc();
$nombre = $row['Nombre'];
$apellidos = $row['Apellidos'];
$telefono = $row['Telefono'];
$usuario = $row['Usuario'];
$contrasena = $row['Contrasena'];
$result = array();
$result["nombre"] = $nombre;
$result["apellidos"] = $apellidos;
$result["telefono"] = $telefono;
$result["usuario"] = $usuario;
$result["contrasena"] = $contrasena;
ChromePhp::warn($result);
ChromePhp::warn(json_encode($result));
echo json_encode($result);
}
}
此方法必须向ajax请求返回JSON,但由于错误:parsererror,因此无法到达success方法
我试过使用数据类型:“json”(这是我出现错误的时候),但没有它(它认为是html)。我也尝试过使用和不使用contentType以及在我的php:header('Content-type:application/json;charset=utf-8')中使用
我的json编码如下所示:
{"nombre":"Susana","telefono":"56765336","usuario":"susa"}
我不知道我是否需要更多的方法,因为我是在Wordpress中使用的,或者我的代码中有错误
任何帮助都将不胜感激。提前感谢:)如果您在Wordpress中执行此操作,我将使用内置的
wpdb
来处理数据库连接和结果。像这样:
function cargaAlumno() {
global $wpdb;
$ids = $_POST['ids'];
$sql = $wpdb->get_results(
$wpdb->prepare("
SELECT *
FROM Alumnos
WHERE id = '$ids'
")
);
echo json_encode($sql);
exit();
}
还要记住,这会进入themes functions.php文件
记住将其挂接到wp_ajax钩子中:
add_action( 'wp_ajax_nopriv_cargaAlumno', 'cargaAlumno' );
add_action( 'wp_ajax_cargaAlumno', 'cargaAlumno' );
然后在ajax中:
$("#tblAlumnos").on("click", ".editar", function(event) {
var rowID = $(this).parents('tr').attr('id');
$.ajax({
type: 'POST',
url: ajaxurl, //this is a wordpress ajaxurl hook
data: {'table': 'alumnos', 'action': 'cargaAlumno', 'ids': rowID}, // You didn't use the correct action name, it's your function name i.e. cargaAlumno
//dataType: 'json', dont need this
success: function(result) {
//Parse the data
var obj = jQuery.parseJSON(result);
console.log(obj[0].nombre); // I'm guessing nombre is your db column name
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
alert(jqXHR.status);
alert(jqXHR);
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
这个js文件需要添加到你的主题中,才能与上面修改过的函数()一起工作
如果您还需要帮助或有任何其他问题,请告诉我。不确定您是否只提供了特定的代码行,或者这就是全部内容,无论如何,这肯定是而不是您应该如何在WordPress中处理AJAX请求:
- 对于需要身份验证的操作,应该使用
;对于不需要身份验证的操作,应该使用wp\u ajax\uu
wp\u ajax\u nopriv\uu
- 您应该为此函数创建一个操作,并使用
admin\u url()通过
发送请求admin ajax.php
- 您应该使用
创建nonce,并使用wp\u create\u nonce()
wp\u verify\u nonce()
- 在检查
$\u服务器['HTTP\u X\u REQUESTED\u WITH']时,应限制对AJAX文件的直接访问。]
global $wpdb;
$query = "SELECT * FROM table_name";
$query_results = $wpdb->get_results($query);
请按照以下结构进行总结:
前端(php文件):
<?php
$ajax_nonce = wp_create_nonce("change_to_action_name");
$ajax_link = admin_url('admin-ajax.php?action=change_to_action_name&nonce=' . $ajax_nonce);
?>
<a class="do_ajax" href="#" data-ajax_link="<?php echo ajax_link; ?>" data-ajax_param="other_param">DO AJAX</a>
<input id="param" value="" />
$('.do_ajax').click(function () {
var ajax_link = $(this).attr('data-ajax_link');
var param = $(this).attr('data-ajax_param');
if (ajax_link && param) {
$.ajax({
type: "post",
dataType: "json",
url: ajax_link,
data: {
param: param,
},
success: function (response) {
if (response.type == "success") {
/*Get/updated returned vals from ajax*/
$('#param').val(response.new_param);
console.log('ajax was successful');
} else if (response.type == "error") {
console.log('ajax request had errors');
}else{
console.log('ajax request had errors');
}
}
});
} else {
console.log('ajax not sent');
}
});
add_action("wp_ajax_change_to_action_name", "change_to_action_name");
add_action("wp_ajax_nopriv_change_to_action_name", "change_to_action_name");
function change_to_action_name()
{
if (!wp_verify_nonce($_REQUEST['nonce'], "change_to_action_name")) {
exit("You think you are smart?");
}
$param = $_REQUEST['param'];
/*php actions goes here*/
$actions_success=0;
if($actions_success){
/*Query db and update vals here*/
$new_param = "new_val";
$result['new_param'] = $new_param;
$result['type'] = "success";
}else{
$result['type'] = "error";
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: " . $_SERVER["HTTP_REFERER"]);
}
die();
}
函数文件(Functions.php文件):
<?php
$ajax_nonce = wp_create_nonce("change_to_action_name");
$ajax_link = admin_url('admin-ajax.php?action=change_to_action_name&nonce=' . $ajax_nonce);
?>
<a class="do_ajax" href="#" data-ajax_link="<?php echo ajax_link; ?>" data-ajax_param="other_param">DO AJAX</a>
<input id="param" value="" />
$('.do_ajax').click(function () {
var ajax_link = $(this).attr('data-ajax_link');
var param = $(this).attr('data-ajax_param');
if (ajax_link && param) {
$.ajax({
type: "post",
dataType: "json",
url: ajax_link,
data: {
param: param,
},
success: function (response) {
if (response.type == "success") {
/*Get/updated returned vals from ajax*/
$('#param').val(response.new_param);
console.log('ajax was successful');
} else if (response.type == "error") {
console.log('ajax request had errors');
}else{
console.log('ajax request had errors');
}
}
});
} else {
console.log('ajax not sent');
}
});
add_action("wp_ajax_change_to_action_name", "change_to_action_name");
add_action("wp_ajax_nopriv_change_to_action_name", "change_to_action_name");
function change_to_action_name()
{
if (!wp_verify_nonce($_REQUEST['nonce'], "change_to_action_name")) {
exit("You think you are smart?");
}
$param = $_REQUEST['param'];
/*php actions goes here*/
$actions_success=0;
if($actions_success){
/*Query db and update vals here*/
$new_param = "new_val";
$result['new_param'] = $new_param;
$result['type'] = "success";
}else{
$result['type'] = "error";
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: " . $_SERVER["HTTP_REFERER"]);
}
die();
}
您当前的代码包含许多安全缺陷,因此非常建议您对其进行更新并使用上述方法
干杯 您遇到了什么错误?parsererror当ajax请求从我知道的php函数@subhashShipuf获得响应时,
$wpdb->prepare
处理安全性。还有什么是$actions\u success
?$actions\u success是一个标志,当某个特定函数成功时,该标志应设置为1,以便能够使用$result['type']发送相关响应,这只是一个演示。此外,$wpdb->prepare
处理数据库查询的安全性(无论如何都是最佳实践),与上面示例中解释的AJAX安全性无关。非常感谢,我现在知道我的函数必须在functions.php中,并且我必须在操作中使用它的名称,但是结果是一样的:-如果我有行数据类型:'json'有一个状态为200的解析器错误-如果我没有它,结果是html,我有以下错误:Uncaught SyntaxError:Unexpected token<在json中的位置0,我不知道问题在哪里,因为我认为我的函数返回的json具有有效的结构,但是ajax没有将其识别为json。你知道为什么会这样吗?真奇怪。你有任何重定向的地方为该网站?例如,如果未登录,则重定向到登录页面。或者如果订阅者不允许它们出现在仪表板中?如果用户已登录并且没有在my.php类的Beggining中将其重定向到错误页面,我将使用session_start()进行检查,但在functions.php或my.jsI中没有类似的问题。我改变了方向。修复方法是删除我添加的重定向,然后添加了一个模板重定向,这是一个wordpress挂钩。我删除了重定向,但没有任何更改。它不断返回html而不是json。