2014-10-03 56 views
0

我通過$.ajax()方法提交表單。我的要求是這樣的:jQuery ajax請求處理不同類型的響應

 $.ajax(url, { 
      type: "POST", 
      contentType: "application/x-www-form-urlencoded; charset=UTF-8", 
      dataType: "html json", 
      data: formData, 
      headers: { 
       "X-Requested-With": "XMLHttpRequest" 
      } 
     }).done(function (result) { 
       //handle correct json response or html response 
     }).fail(function (jqXHR, textStatus, errorThrown) { 
      console.log(jqXHR); 
      console.log(textStatus); 
      console.log(errorThrown.stack); 
     }); 

當服務器返回一個JSON響應時,所有的工作都被忽略。但是,當響應是HTML格式,執行fail()回調(響應的狀態代碼是200 - OK)和errorThrown.stack爲這個值:

"SyntaxError: Unexpected token < 
    at Object.parse (native) 
    at jQuery.extend.parseJSON (http://localhost/Scripts/jquery-1.10.2.js:550:23) 
    at ajaxConvert (http://localhost/Scripts/jquery-1.10.2.js:8429:19) 
    at done (http://localhost/Scripts/jquery-1.10.2.js:8185:15) 
    at XMLHttpRequest.jQuery.ajaxTransport.send.callback (http://localhost/Scripts/jquery-1.10.2.js:8778:8)" 

所以我認爲它正試圖HTML的解析JSON,而不是。我不明白,因爲我已經設置了dataType選項"html json" ...

以下是關於請求/響應的一些信息:

請求頭

Accept:text/html, */*; q=0.01 
Accept-Encoding:gzip,deflate 
Accept-Language:pt-PT,pt;q=0.8,en-US;q=0.6,en;q=0.4 
Connection:keep-alive 
Content-Length:2386 
Content-Type:application/x-www-form-urlencoded; charset=UTF-8 
X-Requested-With:XMLHttpRequest 

響應頭

Cache-Control:private, s-maxage=0 
Content-Length:56392 
Content-Type:text/html; charset=utf-8 
Date:Fri, 03 Oct 2014 09:52:13 GMT 
Server:Microsoft-IIS/8.5 
Vary:Accept-Encoding 
X-AspNet-Version:4.0.30319 
X-AspNetMvc-Version:4.0 
X-Powered-By:ASP.NET 

這是爲什麼發生了什麼?

解決方案(基於@Oscar布特響應)

 $.ajax(url, { 
      type: "POST", 
      contentType: "application/x-www-form-urlencoded; charset=UTF-8", 
      dataType: "html", 
      data: formData, 
      headers: { 
       "X-Requested-With": "XMLHttpRequest" 
      } 
     }).done(function (result) { 
      try { 
       var jsonResult = $.parseJSON(result); 
       //handle json result 
      } catch (e) { 
       $("#myDiv").html(result); //handle html result 
      } 
     }).fail(function (jqXHR, textStatus, errorThrown) { 
      console.log(jqXHR); 
      console.log(textStatus); 
      console.log(errorThrown.stack); 
     }); 

我想用try/catch是不是最好的方法,所以我聽其他選項。

+0

你分析實際的請求和響應(例如使用瀏覽器的Web控制檯),並檢查響應('內容Type')的實際返回類型? – 2014-10-03 09:48:18

+0

@JanakaBandara我更新了我的問題,爲什麼信息。 – amp 2014-10-03 09:55:55

回答

1

你在dataType中的意思是「將html響應視爲JSON」。

dateType函數中的2個值並不意味着它可以處理2種類型。 它的意思是「把第一個當作第二個」。

所以錯誤是可悲的正確。當html進入時,它被視爲JSON。 解析,以及...因爲它不是JSON,但實際上HTML失敗。

該函數的意思是「語法正確的json,但帶有html頭」。 您的迴應可能是「帶html標題的語法正確的html」,因此輸出中的「<」。

也許對你有一種解決方法使用try {} catch(e){}函數?

這裏具體的數據類型的解釋: http://api.jquery.com/jquery.ajax/

+0

我誤解了'dataType'的用法。我會用基於這個響應的解決方案更新我的問題,但我認爲使用'try/catch'不是最好的方法,所以我正在聆聽其他解決方案... – amp 2014-10-03 10:37:29