$.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
그래서 난 다른 옵션을 청취하고 가장 좋은 방법 아니다 사용하여 생각합니다.
당신이 (예를 들어, 브라우저의 웹 콘솔 사용) 실제 요청과 응답을 분석했고, 응답 ('내용-Type')의 실제 반환 유형을 확인? –
@JanakaBandara 내 질문에 대한 정보가 업데이트되었습니다. – amp