思路:可以将TP6返回信息提交到一个新的页面,然后打开查看,避免和原来的文档混淆在一起。 代码:
//1.常规写法
$.ajax({
type: "post",
url: "add_answer_post.html",
data: data,
success: function (response) {
if (response == 'success') {
message('提交成功', 2);
}
},
error: function (error) {
// 打开新窗口并写入内容
const newPageContent = error.responseText;
const newWindow = window.open('', '_blank');
if (newWindow) {
newWindow.document.write(newPageContent);
newWindow.document.close();
} else {
console.error('无法打开新窗口,请检查浏览器设置。');
}
}
});
//2.使用formdata对象时候使用
$.ajax({
url: 'class_update_post.html', // TP6 后端接口地址(路由对应)
type: 'POST', // 上传文件必须使用 POST 方法
data: formData, // 提交的数据:FormData 对象
// 关键配置:禁用 jQuery 对数据的序列化(否则文件无法上传)
processData: false,
// 关键配置:不设置请求头的 Content-Type(让浏览器自动处理为 multipart/form-data)
contentType: false,
dataType: 'html', // 这里可配置为html或者json类型,只有html才可以返回页面形式提示
success: function (res) {
message('栏目修改成功!', 2);
},
error: function (error) {
// 打开新窗口并写入内容
const newPageContent = error.responseText;
const newWindow = window.open('', '_blank');
if (newWindow) {
newWindow.document.write(newPageContent);
newWindow.document.close();
} else {
console.error('无法打开新窗口,请检查浏览器设置。');
}
}
});
补充知识:
常见的 dataType 取值:
| 值 | 说明 |
|---|---|
'xml' | 返回 XML 文档,可用 jQuery 进行解析。 |
'html' | 返回纯 HTML 字符串。 |
'script' | 返回 JavaScript 代码。jQuery 会自动执行它(除非设置了 cache: true)。 |
'json' | 将响应内容解析为 JSON 对象(使用 JSON.parse())。如果 JSON 格式无效,请求会失败。 |
'jsonp' | 用于跨域请求,通过动态 <script> 标签加载并执行回调函数。 |
'text' | 纯文本字符串。 |
null 或未指定 | jQuery 会根据 HTTP 响应头中的 Content-Type 自动推断数据类型(智能猜测)。 |