# AJAX ###### tags: `Learning` ## 適用於 某次遇到狀況是: 前端 Dialog 的操作去 Call 後端,然後,後端的程式碼無論如何都會直接導回主頁面,一時驚慌不知道怎麼丟回提示給前端跟 User 說後端有錯這樣 解: 後端拋 Exception,前端 Ajax Error 去處理 --- ## Url 遇到 Undefined Url 的 Default 為 Current Page ( 當前 URL ) 實際遇到 Undefined 的時候會去抓預設值! --- ## Type Delete 的呼叫方法 ``` $.ajax({ url: '@ValueService.NorthwindDataWebApiUrl.Employee/' + id, //參數放在 url 上 type: 'Delete', success: function () { alert('真的刪除了ㄏㄏ,打我阿笨蛋!!'); Reload(); }, error: function (xhr) { alert('刪除失敗\r\n' + '回應代碼: ' + xhr.status + '\r\n' + '錯誤訊息: ' + xhr.responseText); console.log('刪除失敗\r\n' + '回應代碼: ' + xhr.status + '\r\n' + '錯誤訊息: ' + xhr.responseText); } }) ``` [參考-Call by WebApi Delete method using AJAX](https://stackoverflow.com/questions/29123885/call-by-webapi-delete-method-using-ajax) --- ## Error 錯誤訊息處理 * 如果接回來的是 Html ``` error: function (xhr) { var dom_nodes = $($.parseHTML(xhr.responseText)); alert(dom_nodes.filter('title').text()); } ``` * 接回來的是 Json ``` error: function (xhr) { alert('刪除失敗\r\n' + '回應代碼: ' + xhr.status + '\r\n' + '錯誤訊息: ' + xhr.responseText); console.log('刪除失敗\r\n' + '回應代碼: ' + xhr.status + '\r\n' + '錯誤訊息: ' + xhr.responseText); } ``` --- ## 若 Ajax 呼叫的方法,是 return RedirectToAction,結果會被視為 error 真要用 return RedirectToAction 的話,Ajax 的 Success 和 Error 必須是不需要處理事情的,才不會有影響 不然可以用另一個方法: Action: > return Json(new { redirectToUrl = Url.Action("action", "contoller") }); View: > success: function (response) { window.location.href = response.redirectToUrl; } [參考-ASP.NET MVC RedirectToAction doesn't work after AJAX Post from view ](https://stackoverflow.com/questions/47903390/asp-net-mvc-redirecttoaction-doesnt-work-after-ajax-post-from-view)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up