【问题标题】:Error: SyntaxError: Unexpected token < in JSON错误:SyntaxError:JSON 中的意外标记 <
【发布时间】:2020-10-11 22:58:39
【问题描述】:

我知道为什么在 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);
    }

我的视图有调用方法的 AJAX:

    <input class="btn btn-danger deleteButton" value="Delete Your Profile">

有一个模态窗口,在是,执行 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;
        }); 

【问题讨论】:

  • 嗨,你有errorMessage = "Server error on deleting the user profile. Reason:...这不是json。
  • 该消息被发回,AJAX 处理它就好了。我在视图中显示它OK。问题是当我有一个好的情况并进行重定向时,它返回时没有 JSON。另外,我如何将其传递回 JSON?

标签: jquery ajax asp.net-mvc


【解决方案1】:

试试这个方法可能有用。

控制器

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
        }
  });

【讨论】:

  • Hardik...帮助我解决了我的问题。我在上面发布了解决方案。
【解决方案2】:

我的解决问题的代码(它不再进行重定向并且总是发回一个 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({
            type: 'POST',
            url: '@Url.Action("DeleteUserProfile", "UserProfile")',
            dataType: "json",
            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");
            }
 });

【讨论】:

    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 2018-08-30
    • 1970-01-01
    • 2021-06-30
    相关资源
    最近更新 更多