gpt4 book ai didi

javascript - .NET MVC JSON Post Call 响应未完成或成功

转载 作者:行者123 更新时间:2023-12-02 17:55:15 25 4
gpt4 key购买 nike

我是 .NET MVC 新手,所以请耐心等待。

我编写了一个函数,当文本区域控件上有模糊操作时会触发该函数:

     function extractURLInfo(url) {
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
complete: function (data) {
alert(data);
},
success: function (data) {
alert(data);
},
async: true
})
.done(function (r) {
$("#url-extracts").html(r);
});
}

jQuery(document).ready(function ($) {
$("#input-post-url").blur(function () {
extractURLInfo(this.value);
});
});

这工作正常并且会击中 Controller :

[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();

return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}

如果 URL 有效,我会得到预期的结果;它将返回一个部分 View 到 .done() 函数,我只是在代码中显示它。但是,如果 URL 无效,我希望它能够完成、成功或完成(我一直在尝试查看它会击中哪个,但没有运气!)并对返回的数据执行某些操作。我在某个时刻触发了完成或成功,但数据是“未定义”的。有人可以帮我解决这个问题吗?

谢谢!

最佳答案

在这两种情况下,您的 Controller 操作都会返回 200 状态代码,因此它会触发您的 success 回调:

$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
if (data.message) {
// Your controller action return a JSON result with an error message
// => display that message to the user
alert(data.message);
} else {
// Your controller action returned a text/html partial view
// => inject this partial to the desired portion of your DOM
$('#url-extracts').html(data);
}
}
});

但是当然,更好且语义正确的方法是在发生错误时设置正确的状态代码,而不是仅仅返回大约 200 个状态代码:

[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();

return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
Response.StatusCode = 400;
Response.TrySkipIisCustomErrors = true;
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}

然后在 AJAX 调用中您将适本地处理这些情况:

$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
$('#url-extracts').html(data);
},
error: function(xhr) {
if (xhr.status == 400) {
// The server returned Bad Request status code
// => we could parse the JSON result
var data = JSON.parse(xhr.responseText);

// and display the error message to the user
alert(data.message);
}
}
});

另外,不要忘记您有一些返回错误消息的标准方法,您可以订阅全局 .ajaxError() jQuery 中的处理程序,而不是将此代码放在所有 AJAX 请求中。

关于javascript - .NET MVC JSON Post Call 响应未完成或成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21007207/

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