![](/img/trans.png)
[英]JQuery JSON POST request to ASP.NET MVC controller does not hit end-point, but manual use of route works correctly
[英].NET MVC JSON Post Call response does not hit complete or success
我是.NET MVC的新手,所以請耐心等待。
我編寫了一個函數,當textarea控件上有模糊操作時會觸發該函數:
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);
});
});
這工作正常,將擊中控制器:
[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有效,我會得到預期的結果; 它會將部分視圖返回到.done()函數,我只是在代碼中顯示它。 但是,如果URL無效,我希望它能夠完成,成功或完成(我一直在玩它以查看它將會命中但沒有運氣!)並對返回的數據執行某些操作。 我在某些時候觸發了完整或成功,但數據是“未定義的”。 有人可以幫我解決這個問題嗎?
謝謝!
在這兩種情況下,您的控制器操作都會返回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);
}
}
});
另外,請不要忘記您有一些標准方法可以返回錯誤消息,您可以在jQuery中訂閱全局.ajaxError()
處理程序,而不是將此代碼放在所有AJAX請求中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.