jQuery Ajax请求状态200但返回parseError解析错误排查求助
问题原因
你遇到的parseError本质是后端返回内容不符合JSON格式,jQuery按照dataType: 'json'强制解析非JSON内容时就会抛出解析错误,和HTTP状态码无关。
具体错误点
- 后端无匹配结果分支直接返回纯文本
no posts found,不是合法JSON结构 - PHP代码中未定义
$args变量,搜索参数为空时执行new WP_Query( $args )会抛出PHP警告,警告内容会混入返回结果,破坏JSON格式 - 前端无结果提示的HTML标签闭合错误,
</[li]>是非法写法 - 前端对空结果的判断逻辑有误:
jQuery.isEmptyObject()用于判断空对象,后端返回空数组的话该判断会失效
修复方案
1. 修复PHP后端代码
function my_ajax_filter_search_callback() { header("Content-Type: application/json"); $meta_query = array('relation' => 'AND'); $search_query = null; if(isset($_GET['search'])) { $search = sanitize_text_field( $_GET['search'] ); $search_query = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => -1, 's' => $search ) ); } else { // 初始化空查询参数,避免未定义变量报错 $args = []; $search_query = new WP_Query( $args ); } $result = array(); if ( $search_query->have_posts() ) { while ( $search_query->have_posts() ) { $search_query->the_post(); $result[] = array( "id" => get_the_ID(), "title" => get_the_title(), "content" => get_the_content(), "permalink" => get_permalink(), "poster" => wp_get_attachment_url(get_post_thumbnail_id(get_the_ID()),'full') ); } wp_reset_query(); } // 所有情况统一返回JSON结构,空结果直接返回空数组 echo json_encode($result); wp_die(); }
2. 修复前端AJAX代码
$.ajax({ url : ajax_url, dataType: 'json', contentType: "application/json", data : data, beforeSend : function ( e ) { e.setRequestHeader('Accept', 'application/json; charset=utf-8') }, success : function(response) { mafs.find("ul").empty(); // 用数组长度判断是否有结果 if(response.length > 0){ for(var i = 0 ; i < response.length ; i++) { var html = "<li id='movie-" + response[i].id + "'>"; html += " <a href='" + response[i].permalink + "' title='" + response[i].title + "'>"; html += " <img src='" + response[i].poster + "' alt='" + response[i].title + "' />"; html += " <div class='movie-info'>"; html += " <h4>" + response[i].title + "</h4>"; html += " <p>" + response[i].content + "</p>"; html += " </div>"; html += " </a>"; html += "</li>"; mafs.find("ul").append(html); } } else { // 修复标签闭合错误 var html = "<li><p class='no-result'>No matching movies found. Try a different filter or search keyword</p></li>"; mafs.find("ul").append(html); } }, error: function(errorThrown){ console.log(errorThrown); } });
内容的提问来源于stack exchange,提问作者ccmanz
相关产品推荐
相关产品推荐

