아약스 호출을 통해 Json 표기법에서 오류를 테스트하려고합니다. 이것은 내 서버 방법asp.net에서 json 오류가 작동하지 않습니다.
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string publicarError()
{
try
{
throw new Exception("error");
}
catch (Exception ex)
{
Dictionary<string, object> error = new Dictionary<string, object>();
error.Add("success", false);
error.Add("message", "Something really bad happened");
string output = JsonConvert.SerializeObject(error);
return output;
}
}
입니다 이건 내 아약스 전화
$.ajax({
type: "POST",
url: pageUrl + '/publicarError',
data: '{valor: ' + $('#<%=classroomDropDownList.ClientID%>').val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() { alert('ok'); },
error: function (xhr, textStatus, exceptionThrown) {
var json = xhr.responseText;
var result = [];
result = eval('(' + json + ')');
var errorMessages = [];
//this ugly loop is because List<> is serialized to an object instead of an array
for (var key in result) {
errorMessages.push(result[key]);
}
$('#result').html(errorMessages.join("<br />"));
},
하지만 예제를 실행하면 항상 오류 하나 succes에 기능에 입력되지 않습니다.
나는 이유를 모른다. 실수가 있습니까?
JQuery는 유효한 응답만을 찾고 있습니다. 귀하의 메서드는 예외의 일부로 유효한 JSON을 반환하고 HttpStatus를 변경하지 않으므로 JQuery는 그 차이를 알 수 없습니다. ajax 호출에서 성공 (결과) 함수 내에서 JSON.Stringify (result)를 경고하면 오류 객체가 표시됩니다. – nixkuroi
좋은 점은 경고를 보도록하겠습니다. HttpStatusCode 메서드가 정적이기 때문에 변경할 수 없습니다. 그래서 정적 메서드 Context.Response.StatusCode에 액세스하는 방법을 모르겠다 –