Jquery 如何使用ajax调用json控制器而不重定向到页面
我试图用ajax调用一个MVC控制器,如下所示Jquery 如何使用ajax调用json控制器而不重定向到页面,jquery,ajax,asp.net-mvc,json,Jquery,Ajax,Asp.net Mvc,Json,我试图用ajax调用一个MVC控制器,如下所示 function programare() { $.ajax({ url: "@Url.Action("Programeaza")", type: "POST", dataType: "json", data: { name : $("#name").val() , surnume : $("#surnume").val()
function programare() {
$.ajax({
url: "@Url.Action("Programeaza")",
type: "POST",
dataType: "json",
data: {
name : $("#name").val()
, surnume : $("#surnume").val()
},
error: function (response) {
if (!response.Success)
alert("Server error.");
},
success: function (response) {
if (!response.Success)
alert("Form Error.");
}
});
}
我的控制器方法如下所示:
public JsonResult Programeaza(ProgramareModel input) {
if(String.IsNullOrWhiteSpace(input.name)){
return Json(new {Success = false});
}
return Json("OK");
}
$('#programare').on('click', function(event){
event.preventDefault();
programare();
}
调用控制器后,我被重定向到Programare/Programeaza
页面,该页面显示“OK”或{“Success”:false},而不是从ajax执行Success或error函数
我只想将消息“OK”或“Server error”显示为警报,并保持在同一页面上
编辑:如果我添加
async: false,
对于ajax,调用success函数并显示“OK”消息,但之后它仍然重定向到显示Json内容的页面
在发出警报消息后,我应该如何使其停止
$(function () {
$("#programare").click(programare);
});
html:
Programeaza
试试看
Json Ajax代码
$.post("/BindInventory/CheckItem", { input: name }, function (result) {
alert(reselt);
});
控制器
public JsonResult Programeaza(ProgramareModel input) {
var str ="OK";
if(String.IsNullOrWhiteSpace(input.name)){
return Json(new {Success = false});
}
return JsonResult(str, JsonRequestBehavior.AllowGet);
}
按照以下方式创建jquery-
<script>
function Click() {
$.ajax({
url: "@Url.Action("Programeaza")",
type: "POST",
dataType: "json",
data: {
name: $("#name").val()
, surname: $("#surname").val()
},
error: function (response) {
if (!response.Success)
alert("Server error.");
},
success: function (response) {
if (response == 'OK')
alert(response);
else
alert(response.Success);
}
});
}
</script>
运行应用程序时,您会看到以下屏幕-
当在表格中没有输入的情况下输入时,您会得到-false
当有输入时,您会在警报中得到OK
并且没有重定向您必须防止表单提交的默认行为。用下一种方法更改代码:
function programare() {
$.ajax({
url: "@Url.Action("Programeaza")",
type: "POST",
dataType: "json",
data: {
name : $("#name").val()
, surnume : $("#surnume").val()
},
error: function (response) {
if (!response.Success)
alert("Server error.");
},
success: function (response) {
if (!response.Success)
alert("Form Error.");
}
});
return false; // add this line;
}
文档会看到您正在提交一个表单,默认情况下这是一个同步操作,并导致新页面加载 您需要按如下方式处理单击事件:
public JsonResult Programeaza(ProgramareModel input) {
if(String.IsNullOrWhiteSpace(input.name)){
return Json(new {Success = false});
}
return Json("OK");
}
$('#programare').on('click', function(event){
event.preventDefault();
programare();
}
什么时候调用ajax调用、表单提交、按钮单击等?我在按钮单击上调用ajax方法显示调用ajax调用的代码。$(函数(){$(“#programare”)。单击(programare);});Programeaza@user3234688如果我的帖子有帮助,请你把它标记为答案,这将有助于其他人找到解决方案。
$('#programare').on('click', function(event){
event.preventDefault();
programare();
}