2014-10-03 1 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 응답을 반환하면 모두 예상대로 작동합니다.

"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을 구문 분석하려고 생각 : - 응답이 HTML을 때 단, fail() 콜백 실행이 값 (응답의 상태 코드가 200 OK) 및 errorThrown.stack .

요청 헤더

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 

응답 헤더 : 나는 "html json"dataType 옵션을 설정 때문에 요청/응답에 대한 몇 가지 정보입니다

은 다음과 ... 이해가 안 돼요

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

당신이 (예를 들어, 브라우저의 웹 콘솔 사용) 실제 요청과 응답을 분석했고, 응답 ('내용-Type')의 실제 반환 유형을 확인? –

+0

@JanakaBandara 내 질문에 대한 정보가 업데이트되었습니다. – amp

답변

1

dataType에서 말하는 것은 "html 응답을 JSON으로 처리합니다"입니다.

2 dateType 함수의 값이 2 가지 유형을 처리 할 수있는 것은 아닙니다. "첫 번째 것을 두 번째로 취급"을 의미합니다.

그래서 오류가 슬프게 맞습니다. HTML이 들어 오면 JSON으로 처리됩니다. 구문 분석은 JSON이 아니기 때문에 실제로 HTML에서는 실패합니다.

이 함수는 "구문 올바른 json이지만 html 헤더가있는"것을 의미합니다. 귀하의 응답은 아마도 "구문 올바른 html 헤더 html"이므로 출력에 "<"이 표시됩니다.

시도 {} catch (e) {} 기능을 사용하고 계신지요?

다음 데이터 유형 설명

: http://api.jquery.com/jquery.ajax/

+0

'dataType'의 사용법을 오해했습니다. 이 응답을 기반으로하는 솔루션으로 내 질문을 업데이트 하겠지만'try/catch'를 사용하는 것이 최선의 방법이 아니므로 다른 솔루션을 듣고 있습니다 ... – amp