Rails 如何簡單回應 AJAX? 就用 json 啊

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
633   0  
·
2018/03/26
·
3 mins read


在 AJAX 呼叫 Rails 的 Controller 後,我想最重要的就是知道 server 這邊處理的結果,一般我們都會用一個與 controller 同名的 view.js 去自動執行,一般都是 refresh 網頁啊,或是跳到另一個網址等等。

但有沒有更簡單的方法啊,我是這樣用的,直接上 code,少囉唆:

AJAX side:

// set the params
var id = $('#name').attr('data-name');
var a = JSON.stringify( Array );
$.ajax({
  type: "patch",
  url: "/controller_name/action/",
  data: { id: id, array: array },
  dataType: "json", /* 重點一 */
  error: function (jqXHR, textStatus, errorThrown) {
  // server 回應有問題.... 重點二
  whatever_fail();
  },
  success: function(data, textStatus, jqXHR) {
    // server 回應正常,再來看看處理的結果
  if (data.success != "true") { /* 重點三 */
// server 回應正常,下一步?
  whatever_success();
};
  }
});

Server side:

def action
  # 你的程式碼,重點四,用個變數來記錄結果,這裡是用 error 字串
  # return with json, 使用 data, 你可以用這傳回任何值
respond_to do |format|
if error.blank? # 重點五
format.js { render status: 200, json: {success: true, status: "ok", data: "ok" } }
else
format.js { render status: 200, json: {success: false, status: "fail", data: error } }
end
end
end

重點說明:

  • 重點一:AJAX 要指定回應的資料要以 json 的方式處理,所以 dataType: "json",
  • 重點二:AJAX 收到錯誤是指 server side 回應錯誤,一般是指認證不對啦,不處理啦,斷線啦,你也可以人工製造錯誤,在重點五中,把 status: 200 改成 4xx,5xx 等等,我不確定到底是一定要 200 還是二字頭都會被當成成功,但是不是二字頭是一定會被認回是錯誤的,用 status 碼來做結果判斷我不喜歡,應為在瀏覽器上,如果使用者打開發展工具,是會在 console 上看到錯誤回應的,當然,誰沒事會開發展工具,也對啦,所以是“我不喜歡。”
  • 重點三:就用 json 傳回來的值來當結果,這就可以用來判斷下一步了,發展工具上也不會顯示錯誤, json 也可以傳回來幾乎任何值,所以就很簡單方便好用,在這個例子中,我是使用 data.success 來傳結果,你可以用任何變數名啦,可以看重點五的指定方式。
  • 重點四:就在你程式中用個變數來記錄錯誤,這是我覺得最簡單的方法。
  • 重點五:這就是寫入 json 的方式,夠簡單吧,json: {success: false, status: "fail", data: error },這裡是說:data.success = false,data.status = "fail" 以及 data.data = error 字串。

AJAX 很好用,也方便,但是使用時,要盡量不要呼叫一大堆,畢竟,每一次呼叫都要重啟連線,雖然 AJAX 很快了,但是如果能整合成一個,會方便開發,提高性能,更可以少用很多的 call back。


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

Categories:
Tags:
Total: 695 words


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.