2013-12-23 44 views
1

我有這個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

所以,我怎樣才能使此代碼多功能

+0

是確定你正在解析數組到json_encode()? – underscore

+0

是的JSON數據。但如果返回的數據是html,我不使用'json_encode'。 – laukok

+1

你可以試試這個:'dataType:「json」|| 「html」,'你可以嘗試使用'typeof()'方法來處理返回的數據,如果這是'object',則它將它作爲json處理。 – Jai

回答

4

我不知道是否有更好的辦法,但你可以嘗試...趕上

$.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 
     } 
     } 

}); 
3

本質上,您的代碼只是錯誤 - 如果返回類型可能以不一致的方式變化,則您的服務器端API違反了所有可預測性原則。你的代碼不應該猜測返回數據的類型。

話雖如此,a simple try/catch將有助於解決不穩定的行爲,如果你不想解決它。 IE瀏覽器。

try { 
    if ($.parseJSON(returndata) === false) A; 
} catch(e) { 
    // Treat as HTML here. 
} 

這並不美觀,但這就是你得到一個不可預知的API,開始時並不漂亮。

+0

謝謝。但是這行'if($ .parseJSON(returndata)=== false)'當我傳遞一個json數據時什麼都不做。 – laukok

+1

我剛剛從你的代碼中複製了那部分 - 我的回答是關於規避錯誤,而不是其他問題,你可能會或可能沒有;) –

+0

Aww我看到。謝謝! :) – laukok

-1

可能是你需要處理像這樣

try{ 
var response=jQuery.parseJSON('response from server'); 
if(typeof response =='object') 
{ 
    //control would reach this point if the data is returned as json 
} 
else 
{ 
    //control would reach this point if data is plain text 
    if(response ===false) 
    { 
     //the response was a string "false", parseJSON will convert it to boolean false 
    } 
    else 
    { 
      //the response was something else 
    } 
} 
} 
catch(exp){ 
    //controls reaches here, if the data is html 
} 

既然你需要檢查的HTML數據,以及,你可能需要照顧這個,

也可能需要使用例外的一個try/catch,如果有可能parseJSON將要處理的不是JSON值以外的東西(即HTML)

REF:How can I check if a value is a json object?

編輯:編輯,以使代碼實現的解決方案更精確

+1

將無法​​正常工作,他的整個核心問題是'parseJSON'會引發一個錯誤,所以在問題情況下,大部分代碼都是'無法訪問'的。 –

+0

@NielsKeurentjes:這就是我添加一條消息(用斜體字體表示)** parseJSON **需要包含在try catch塊中以處理返回html數據的異常的原因。 – dreamweiver

+0

@NielsKeurentjes:我編輯了答案,我想現在它的罰款 – dreamweiver