aw.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. Copyright 2009-2010 Igor Polevoy
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. /*
  14. This file is a collection of unobtrusive JS that binds to link_to generated anchors typical for Ajax calls.
  15. author: Igor Polevoy
  16. */
  17. $(document).ready(function() {
  18. $('a[data-link]').bind('click', function() {
  19. var anchor = $(this);
  20. var destination = anchor.attr("data-destination");
  21. var formId = anchor.attr("data-form");
  22. var href = anchor.attr("href");
  23. var _method = anchor.attr("data-method");
  24. var before = anchor.attr("data-before");
  25. var after = anchor.attr("data-after");
  26. var beforeArg = anchor.attr("data-before-arg");
  27. var afterArg = anchor.attr("data-after-arg");
  28. var error = anchor.attr("data-error");
  29. var confirmMessage = anchor.attr("data-confirm");
  30. if(confirmMessage != null ){
  31. if(!confirm(confirmMessage)){
  32. return false;
  33. }
  34. }
  35. //not Ajax
  36. if(destination == null && before == null && after == null && (_method == null || _method.toLowerCase() == "get")){
  37. return true;
  38. }
  39. if (_method == null) {
  40. _method = "get";
  41. }
  42. var type;
  43. if (_method.toLowerCase() == "get") {
  44. type = "get";
  45. } else if (_method.toLowerCase() == "post"
  46. || _method.toLowerCase() == "put"
  47. || _method.toLowerCase() == "delete") {
  48. type = "post";
  49. }
  50. var data = "_method=" + _method;
  51. if (formId != null) {
  52. data += "&" + $("#" + formId).serialize();
  53. }
  54. if(before != null){
  55. eval(before)(beforeArg);
  56. }
  57. $.ajax({ url: href, data: data, type:type,
  58. success: function(data) {
  59. if (after != null)
  60. eval(after)(afterArg, data);
  61. if (destination != null)
  62. $("#" + destination).html(data);
  63. },
  64. error: function(xhr, status, errorThrown) {
  65. if(error != null){
  66. eval(error)(xhr.status, xhr.responseText );
  67. }
  68. }
  69. });
  70. return false;
  71. });
  72. });