SweetAlert2中AJAX发送OTP后无法解析JSON响应的技术求助
解决SweetAlert2中AJAX JSON响应无法处理的问题
问题说明
使用SweetAlert2结合AJAX发送OTP验证码时,AJAX请求已成功收到JSON响应,但无法像常规AJAX那样解析并处理该响应。尝试过response.json()和设置dataType: "JSON"均无效。
核心原因
response.json()是Fetch API的用法,jQuery的$.ajax会自动根据服务器返回的Content-Type头解析JSON,不需要手动调用该方法。- WordPress后端代码未设置正确的JSON响应头,导致jQuery无法自动识别并解析响应内容。
解决步骤
1. 修正PHP后端代码
在输出JSON前添加Content-Type响应头,确保jQuery能自动解析响应:
add_action('wp_ajax_aw_confirm_user_ajax_in_account', 'aw_confirm_user_ajax_in_account'); function aw_confirm_user_ajax_in_account() { // 添加JSON响应头,告知前端返回内容类型 header('Content-Type: application/json'); echo json_encode(array( 'success' => true, 'message' => 'send in', 'loogin' => true, )); die; }
2. 修正SweetAlert2中的AJAX代码
移除无效的response.json()调用,直接返回jQuery已解析好的响应对象即可,同时补充传递用户输入的手机号:
Swal.fire({ title: 'Submit your number for get opt code', input: 'text', inputAttributes: { autocapitalize: 'off' }, showCancelButton: true, inputValue: '0998', confirmButtonText: 'send opt code', showLoaderOnConfirm: true, preConfirm: function () { return $.ajax({ type: 'POST', url: aw_ajax_url, data: { 'action': 'aw_confirm_user_ajax_in_account', // 传递用户输入的手机号,后端才能处理OTP发送 'phone': Swal.getInput().value } }).then(response => { // jQuery已自动解析JSON,直接返回响应对象 return response; }).catch(error => { // 捕获请求错误,展示给用户 Swal.showValidationMessage(`请求失败: ${error}`); }); }, allowOutsideClick: () => !Swal.isLoading() }).then((result) => { if (result.value) { // 现在可以直接访问JSON的属性 console.log(result.value.success); console.log(result.value.message); // 用SweetAlert展示处理结果 Swal.fire({ title: '操作成功', text: result.value.message, icon: 'success' }); } });
额外说明
如果上述修改后仍存在解析问题,可以显式设置$.ajax的dataType: 'json',强制jQuery将响应解析为JSON:
$.ajax({ type: 'POST', dataType: 'json', // 显式指定解析类型 url: aw_ajax_url, data: { ... } })
内容的提问来源于stack exchange,提问作者alex dev
相关产品推荐
相关产品推荐

