我对AJAX和MVC都比较新,我正在尝试进行确认交互。
我要做的是显示一个框,用户将输入一个值并单击提交,然后框将AJAX POST(我认为这就是我应该使用的)到Controller并返回一个true或者假。我似乎无法弄清楚如何使这种交互工作。
如果我运行调试,我可以看到我的值传递给Controller,但它忽略了我的if
语句来检查字符串是否正确。除此之外,我不知道如何返回一个真/假并在我的AJAX中处理它。
到目前为止,这是我的“最佳猜测”。
AJAX / JS
<script type="text/javascript">
function preloadFunc() {
var prompting = prompt("Please enter your password", "****");
if (prompting != null && prompting != null) {
$.ajax({
url: '/Admin/magicCheck',
type: 'POST',
data: {
'magic': prompting
},
success: function () {
//let page load
},
error: function () {
preloadFunc(); //re-ask
}
});
}
else {
window.location.replace("google.com"); //Pressing Cancel
}
}
window.onpaint = preloadFunc();
</script>
控制器
[HttpPost]
public ActionResult magicCheck(string magic)
{
bool success = false;
if (magic == "poof")
{
success = true;
}
else
{
success = false;
}
return RedirectToAction("Index");
}
所有帮助都非常感谢,因为我是新手!
答案 0 :(得分:1)
阅读帖子下面的所有评论,因为这里有很多问题,但就AJMI和回复而言:
更改控制器以返回JSON,如下所示:
[HttpPost]
public ActionResult magicCheck(string magic)
{
bool success = false;
if (magic == "poof")
{
success = true;
}
else
{
success = false;
}
return Json( new { Success = success });
}
现在控制器正在返回JSON,你需要更改你的js来处理它:
$.ajax({
url: '/Admin/magicCheck',
type: 'POST',
data: 'magic=' + prompting, //<-- you didn't need to send JSON for this, you'd have to change your controller if you are going to send a JSON object also... you just need this for now
success: function (resp) {
//let page load
if ( resp.Success ){
// success...
}
else{
//fail
}
},
error: function () {
preloadFunc(); //re-ask
}
});