Fer*_*min 2 asp.net-mvc jquery parse-error
我试图通过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();
}
});
});
Run Code Online (Sandbox Code Playgroud)
我的行动方法是:
[AcceptVerbs(HttpVerbs.Delete)]
public string Delete(int id)
{
// Deletion code
return " ";
}
Run Code Online (Sandbox Code Playgroud)
当我读到某个地方时,我返回一个空字符串,如果内容长度为0则会导致问题,当返回类型为字符串时,我会收到一个警告框,上面写着"错误:错误未定义",第二个警告框为空.
如果我使返回类型为void,则会收到一条警告"Error:parsererror undefined",第二个警告如下:
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
Run Code Online (Sandbox Code Playgroud)
你的jQuery调用期望Json返回请求.所以:
[AcceptVerbs(HttpVerbs.Delete)]
public JsonResult Delete(int id) {
// Deletion code
return Json("");
}
Run Code Online (Sandbox Code Playgroud)
而且我同意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");
}
}
Run Code Online (Sandbox Code Playgroud)