php - php json_encode 响应将 html 发送回 ajax jquery 请求而不是 json
问题描述
对于作为 wordpress 插件的简单联系表单,我在同一页面中创建了一个弹出窗口:
<form method="post" id="w_form" enctype="multipart/form-data">
<label for="first_name" class="text-secondary">First Name</label>
<input id="first_name" type="text" name="first_name" form-control" value="" required="">
<label for="last_name" class="text-secondary">Last Name</label>
<input id="last_name" type="text" name="last_name" form-control" value="" required="">
<button class="btn btn-danger" id="submit" type="submit" value="Submit" name="submit">
Submit
</button>
</form>
其数据将通过 ajax 发送到后端:
$("#w_form").submit( function(event) {
event.preventDefault();
$.ajax({
type: "post",
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
$('#submit').attr("disabled", "disabled");
},
success: function( response ) {
alert( response );
// if ( response.status == 1 ) {
// $('#w_form')[0].reset();
// }
},
error: function (xhr, error) {
console.debug(xhr);
console.debug(error);
},
});
});
传递给同一页面和表单顶部的 php 代码:
if ( isset( $_POST['first_name'] ) ) {
$uploaded_status;
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$to = 'abc@example.com';
$subject = 'test';
$body = 'body';
if ( wp_mail( $to, $subject, $body, '') ) {
$uploaded_status = 1;
} else {
$uploaded_status = 0;
}
if ( $uploaded_status == 1 ) {
$response = array();
$response['status'] = 1;
$response['message'] = 'Your form submitted successfully!';
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($response);
}
}
此过程正常工作并通过电子邮件将表单数据发送到电子邮件地址,但作为:success
ajax 的一部分的响应数据获取 html 内容而不是 json 并返回parsererror
为console.debug(error);
正如我所提到的,以电子邮件形式提交和发送数据可以正常工作,但我没有正确的数据用于响应过程以在提交按钮后控制 UI
解决方案
如果您收到无效的 JSON 数据以响应发送到同一页面的 Ajax 请求,您需要在发送响应之前丢弃任何输出缓冲区,然后立即终止处理,以防止将任何进一步的内容附加到响应流中。
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['first_name'],$_POST['last_name'] ){
ob_clean();# discard any previous buffer data
$uploaded_status;
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$to = 'abc@example.com';
$subject = 'test';
$body = 'body';
if ( wp_mail( $to, $subject, $body, '') ) {
$uploaded_status = 1;
} else {
$uploaded_status = 0;
}
if ( $uploaded_status == 1 ) {
$response = array();
$response['status'] = 1;
$response['message'] = 'Your form submitted successfully!';
header("Content-Type: application/json; charset=utf-8", true);
exit( json_encode( $response ) );#terminate
}
}
推荐阅读
- mysql - 在 codeigniter 中动态加载数据库
- flutter - 未处理的异常:DioError [DioErrorType.CONNECT_TIMEOUT]:连接超时 [5000ms]
- android - 如何在 Kotin 的实例方法中使用构造函数中的属性?
- spring-boot - SpringBoot gzip压缩不再工作
- javascript - 如何在 Jest NodeJS 中对 JSON 结果进行单元测试?
- android - 查看绑定未生成
- wordpress - wp_localize_script 不接受动态值
- php - 按字母顺序按首字母分组
- javascript - typeError:无法在角度 9.0.4 中分配给对象“[object Object]”的只读属性“tView”
- gensim - 如何理解 gensim 的 iter 参数及其对预处理的影响?