gpt4 book ai didi

javascript - 通过javascript调用MVC操作方法但不使用AJAX

转载 作者:行者123 更新时间:2023-11-28 21:03:29 24 4
gpt4 key购买 nike

我有一个带有 3 个参数的 MVC3 操作方法,如下所示:

 var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";

我想通过普通的javascript函数而不是AJAX来调用它(因为没有必要使用AJAX函数)我尝试使用这个功能,但没有成功:

window.location.assign(url);

它没有跳转到 QuestionController 的插入操作。

有人愿意帮助我吗?非常感谢

这是更多细节

我想向数据库插入新问题,但我必须从 CKeditor 获取数据,所以我必须使用下面的这个函数来获取和验证数据

// insert new question
$("#btnDangCauHoi").click(function () {
//validate input data
//chủ đề câu hỏi
var title = $("#txtTitle").val();

if (title == "") {
alert("bạn chưa nhập chủ đề câu hỏi");
return;
}
//nội dung câu hỏi
var content = GetContents();
content = "xyz";
if (content == "") {
alert("bạn chưa nhập nội dung câu hỏi");
return;
}
//danh sách Tag
var listTags = new Array();
var Tags = $("#list_tag").children();

if (Tags.length == 0) {
alert("bạn chưa chọn tag cho câu hỏi");
return;
}

for (var i = 0; i < Tags.length; i++) {
var id = Tags[i].id;
listTags[i] = id;
//var e = listTags[i];
}
var data = {
"_strTitle": title,
"_strContent": content,
"_listTags": listTags.toString()
};
// $.post(url, data, function (result) {
// alert(result);
// });
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
window.location.assign(url); // I try to use this, and window.location also but they're not working
});

此 URL 通过 POST 方法调用下面的 MVC 操作“插入”

    [HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{

try
{
//some code here
}
catch(Exception ex)
{
//if some error come up
ViewBag.Message = ex.Message;
return View("Error");
}
// if insert new question success
return RedirectToAction("Index","Question");
}

如果插入操作成功,它将重定向到索引页面,其中列出所有问题,包括已插入的新问题。如果没有,它将显示错误页面。所以,这就是我不使用 AJAX 的原因

有人能帮帮我吗?谢谢:)

最佳答案

尝试:

window.location = yourUrl;

此外,尝试使用 Fiddler 或其他类似工具来查看是否发生重定向。

编辑:

您的操作需要 HTTP POST 方法,但使用 window.location 将导致 GET 方法。这就是为什么你的操作永远不会被调用的原因。

[HttpPost] 
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
// Your code
}

要么更改为 HttpGet(您不应该这样做),要么使用 jQuery 或其他支持 Ajax 的库来执行 POST。您不应该使用 GET 方法来更新数据。它会给您带来如此多的安全问题,让您在解决问题时不知从何入手。

考虑到您已经在使用 jQuery,您不妨一直使用 Ajax。使用$.post()方法执行HTTP POST操作。

在 $.post() 的回调函数内,您可以在最后返回 false 以防止重定向到错误或索引 View 。

$.post("your_url", function() {
// Do something

return false; // prevents redirection
});

就是这样。

关于javascript - 通过javascript调用MVC操作方法但不使用AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10450851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com