如何解决错误:语法错误:JSON中的意外令牌<
我知道为什么在AJAX完成时会收到此消息,并希望JSON返回。
但是,我对控制器的动作方法进行了编码,以便在一切正常的情况下将其重定向到另一个视图。如果发现错误,请返回JSON-错误消息。
从我正在学习的AJAX角度来看,无论良好(重定向)还是错误情况(我返回JSON),它都将返回JSON。
那么当我在进行重定向并且不以编程方式返回任何内容的情况下很好时,如何在AJAX中进行编码以识别出没有返回JSON?
从某种意义上说,该动作方法可以成功执行,执行删除操作,执行重定向,但是在返回时被捕获,并且得到以下消息:
我的操作方法是:
Task<ActionResult>
如果我尝试
Task<JsonResult>
public async Task<ActionResult> DeleteUserProfile()
{
string errorMessage = String.Empty;
try
{
Some code to call the web api...
using (var client = new HttpClient())
{
Some code...
// Call the web api - HTTP POST.
HttpResponseMessage result = await client.PostAsync(restOfUrl,argsData);
if (result.IsSuccessstatusCode)
{
return RedirectToAction("Index","User");
}
else
{
// The web api sent an error response.
errorMessage = "Server error on deleting the user profile. Reason: " + result.ReasonPhrase;
}
}
}
catch (Exception ex1)
{
Some code...
}
// Return a JSON object to show the error message.
return Json(errorMessage,JsonRequestBehavior.AllowGet);
}
<input class="btn btn-danger deleteButton" value="Delete Your Profile">
有一个Modal窗口,是的,执行AJAX。而且我认为只有在我将错误消息推送到JSON时,它才会回来。
$('.btn-yes11').click(function() {
$('#myModal11').modal('hide');
$.ajax({
type: 'POST',url: '@Url.Action("DeleteUserProfile","UserProfile")',dataType: "json",success: function(jsondata) {
if (jsondata.length > 0)
{
// Set the error message.
$("#jsonErrorMessage").text(jsondata);
// Show.
$("#jsonErrorMessage").css("display","block");
}
else
{
// Hide.
$("#jsonErrorMessage").css("display","none");
}
},error: function(xhr,ajaxOptions,thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserProfile for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
return true;
});
解决方法
尝试这种方式可能会有用。
控制器
public JsonResult Create(MyObject myObject)
{
//AllFine
return Json(new { IsCreated = True,Content = ViewGenerator(myObject));
//Use input may be wrong but nothing crashed
return Json(new { IsCreated = False,Content = ViewGenerator(myObject));
//Error
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { IsCreated = false,ErrorMessage = 'My error message');
}
JS
$.ajax({
type: "POST",dataType: "json",url: "MyController/Create",data: JSON.stringify(myObject),success: function (result) {
if(result.IsCreated)
{
//... ALL FINE
}
else
{
//... Use input may be wrong but nothing crashed
}
},error: function (error) {
alert("Error:" + erro.responseJSON.ErrorMessage ); //Error
}
});
,
用于解决我的问题的代码(不再执行重定向,并且始终发送回JSON对象):
public async Task<JsonResult> DeleteUserProfile()
{
string errorMessage = String.Empty;
bool RedirectSwitch = false;
try
{
Some code to call the web api...
using (var client = new HttpClient())
{
Some code...
// Call the web api - HTTP POST.
HttpResponseMessage result = await client.PostAsync(restOfUrl,argsData);
if (result.IsSuccessStatusCode)
{
// Set the switch so that the AJAX call will go to the User controller.
RedirectSwitch = true;
}
else
{
// The web api sent an error response.
errorMessage = "Server error on deleting the user profile. Reason: " + result.ReasonPhrase;
}
}
}
catch (Exception ex1)
{
Some code...
}
if (errorMessage != "")
{
// Set an error code which will initiate the AJAX function: 'error: function (error) {}'.
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
// Creates JSON representation of anonymous data.
// Return a JSON object.
return Json(new { Redirect = RedirectSwitch,ErrorMessage = errorMessage });
}
Ajax:
$.ajax({
type: 'POST',url: '@Url.Action("DeleteUserProfile","UserProfile")',success: function (result) {
if (result.Redirect)
{
// A successful delete - so go to the User controller. To the index action which returns the Views\User\User.cshtml.
window.location.href = "/User/Index/";
}
},error: function (error) {
// Set the error message from the key/value pair set in the controller: ErrorMessage = errorMessage.
$("#jsonErrorMessage").text(error.responseJSON.ErrorMessage);
// Show it.
$("#jsonErrorMessage").css("display","block");
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。