我有這個ajax請求從我的服務器獲取數據,並且默認情況下dataType
總是html
。但有時它會從服務器返回json,所以我想檢查返回的數據是否是html,然後執行A else執行B.是否有可能?jQuery ajax返回數據:json和html混合?
我的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
所以,我怎樣才能使此代碼多功能?
是確定你正在解析數組到json_encode()? – underscore
是的JSON數據。但如果返回的數據是html,我不使用'json_encode'。 – laukok
你可以試試這個:'dataType:「json」|| 「html」,'你可以嘗試使用'typeof()'方法來處理返回的數據,如果這是'object',則它將它作爲json處理。 – Jai