ASP.NET MVCアプリではJQueryのAjaxのparsererror
-
18-09-2019 - |
質問
私はjQueryのアヤックスのメソッドを介して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を作る場合は、私が言ってアラートを取得「エラー:未定義のparsererrorを」と、次のように、第2の警告は、次のとおりです。
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
解決
私は空の文字列を返すように助言しません。あなたはjQueryの応答をevalしますJSONにデータ型を設定しているので。
あなたは常に論理メッセージを返す必要があります。
return Json(new { success = "true" });
$(tr).remove()
を使用している成功内部 N.B。
あなたのtr変数をまだjQueryオブジェクトであるとして必要はありません
tr.remove
はうまく動作します。
他のヒント
あなたの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");
}
}
所属していません StackOverflow