gpt4 book ai didi

javascript - jQuery ajax 返回数据 : json and html mix?

转载 作者:行者123 更新时间:2023-12-01 02:11:14 24 4
gpt4 key购买 nike

我有一个ajax请求从我的服务器获取数据,默认情况下dataType始终为html。但有时会从服务器返回json,所以我想检查返回的数据是否是html然后执行A否则执行B。可以吗?

我的jquery,

 $.ajax({
type: "GET",
dataType: "html",
url: request_url,
context: $('#meat'),
async: true,
beforeSend: function () {},
success: function (returndata, status, jqXHR) {
if ($.parseJSON(returndata) === false) A;
else B.
}
});

当返回的数据是 html 时,出现此错误,

SyntaxError: JSON.parse: unexpected character

那么我怎样才能使这段代码多功能

最佳答案

我不确定是否有更好的方法,但你可以尝试... catch

$.ajax({
type: "GET",
url: request_url,
context: $('#meat'),
async: true,
beforeSend: function() {
},
success: function (returndata, status, jqXHR) {
var parsed;
try
{
parsed = $.parseJSON(returndata);
// Execute B
}
catch(e)
{
// treat as html then
// do parsing here
parsed = returnData;
// Execute A
}
}

});

关于javascript - jQuery ajax 返回数据 : json and html mix?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20743326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com