【问题标题】:JQuery ajax parsererror in ASP.NET MVC appASP.NET MVC 应用程序中的 JQuery ajax 解析器错误
【发布时间】:2010-11-12 22:15:14
【问题描述】:

我正在尝试通过 JQuery ajax 方法调用 ASP.NET MVC actionMethod。我的代码如下:

$('.Delete').live('click', function() {
    var tr = $(this).parent().parent();

    $.ajax({
        type: 'DELETE',
        url: '/Routing/Delete/' + tr.attr('id'),
        contentType: 'application/json; charset=utf-8',
        data: '{}',
        dataType: 'json',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Error: " + textStatus + " " + errorThrown);
            alert(XMLHttpRequest.getAllResponseHeaders());
        },
        success: function(result) {
            // Remove TR element containing waypoint details
            alert("Success");
            $(tr).remove();
        }
    });
});

而我的操作方法是:

[AcceptVerbs(HttpVerbs.Delete)]
public string Delete(int id)
{
    // Deletion code

    return " ";
}

我在某处读到时返回一个空字符串,如果内容长度为 0,那么它可能会导致问题,当返回类型是字符串时,我会收到一个警告框,上面写着“错误:错误未定义”和第二个警告框是空的。

如果我将返回类型设为 void,我会收到一条提示“错误:解析器错误未定义”的警报,第二个警报如下:

Server: ASP.NET Development Server/9.0.0.0
Date: Wed, 22 Jul 2009 08:27:20 GMT
X-AspNet-Version: 2.0.50727
X-AspNetMvc-Version: 1.0
Cache-Control: private
Content-Length: 0
Connection: Close

【问题讨论】:

  • 嗯,我的答案是一样的,第一!

标签: asp.net-mvc jquery parse-error


【解决方案1】:

我不建议返回空字符串。由于您已将 dataType 设置为 json,因此 jquery 将评估响应。

你应该总是返回一个合乎逻辑的消息。

return Json(new { success = "true" });

N.B里面你使用成功$(tr).remove(); 没有必要,因为您的 tr 变量已经是一个 jQuery 对象,所以 tr.remove 可以正常工作。

【讨论】:

    【解决方案2】:

    您的 jQuery 调用需要 Json 来返回请求。所以:

    [AcceptVerbs(HttpVerbs.Delete)]
    public JsonResult Delete(int id) {
        // Deletion code
        return Json("");
    }
    

    我也同意redsquare,最好返回这样的逻辑消息:

    [AcceptVerbs(HttpVerbs.Delete)]
    public JsonResult Delete(int id) {
        // Deletion code
        return Json(new { Success = true });
    }
    
    //then in your jQuery function you can check the result this way :
    success: function(result) {
        if (result.Success) {
            alert("it was deleted!");
        }
        else {
            alert("something went wrong");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-28
      • 2010-10-13
      • 2020-09-17
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多