github.com/kotovmak/go-admin@v1.1.1/template/types/action/ajax.go (about)

     1  package action
     2  
     3  import (
     4  	"encoding/json"
     5  	"html/template"
     6  	"strings"
     7  
     8  	"github.com/kotovmak/go-admin/context"
     9  	"github.com/kotovmak/go-admin/modules/constant"
    10  	"github.com/kotovmak/go-admin/modules/language"
    11  	"github.com/kotovmak/go-admin/template/types"
    12  )
    13  
    14  type AjaxAction struct {
    15  	BaseAction
    16  	Url         string
    17  	Method      string
    18  	Data        AjaxData
    19  	Alert       bool
    20  	AlertData   AlertData
    21  	SuccessJS   template.JS
    22  	ErrorJS     template.JS
    23  	ParameterJS template.JS
    24  	Event       Event
    25  	Handlers    []context.Handler
    26  }
    27  
    28  type AlertData struct {
    29  	Title              string `json:"title"`
    30  	Type               string `json:"type"`
    31  	ShowCancelButton   bool   `json:"showCancelButton"`
    32  	ConfirmButtonColor string `json:"confirmButtonColor"`
    33  	ConfirmButtonText  string `json:"confirmButtonText"`
    34  	CloseOnConfirm     bool   `json:"closeOnConfirm"`
    35  	CancelButtonText   string `json:"cancelButtonText"`
    36  }
    37  
    38  func Ajax(id string, handler types.Handler) *AjaxAction {
    39  	if id == "" {
    40  		panic("wrong ajax action parameter, empty id")
    41  	}
    42  	return &AjaxAction{
    43  		Url:    URL(id),
    44  		Method: "post",
    45  		Data:   NewAjaxData(),
    46  		SuccessJS: `if (data.code === 0) {
    47                                      swal(data.msg, '', 'success');
    48  																		$.pjax.reload('#pjax-container');
    49                                  } else {
    50                                      swal(data.msg, '', 'error');
    51                                  }`,
    52  		ErrorJS: `if (data.responseText !== "") {
    53  									swal(data.responseJSON.msg, '', 'error');								
    54  								} else {
    55  									swal('error', '', 'error');
    56  								}`,
    57  		Handlers: context.Handlers{handler.Wrap()},
    58  		Event:    EventClick,
    59  	}
    60  }
    61  
    62  func (ajax *AjaxAction) WithAlert(data ...AlertData) *AjaxAction {
    63  	ajax.Alert = true
    64  	if len(data) > 0 {
    65  		ajax.AlertData = data[0]
    66  	} else {
    67  		ajax.AlertData = AlertData{
    68  			Title:              "",
    69  			Type:               "warning",
    70  			ShowCancelButton:   true,
    71  			ConfirmButtonColor: "#DD6B55",
    72  			ConfirmButtonText:  language.Get("yes"),
    73  			CloseOnConfirm:     false,
    74  			CancelButtonText:   language.Get("cancel"),
    75  		}
    76  	}
    77  	return ajax
    78  }
    79  
    80  func (ajax *AjaxAction) AddData(data map[string]interface{}) *AjaxAction {
    81  	ajax.Data = ajax.Data.Add(data)
    82  	return ajax
    83  }
    84  
    85  func (ajax *AjaxAction) SetData(data map[string]interface{}) *AjaxAction {
    86  	ajax.Data = data
    87  	return ajax
    88  }
    89  
    90  func (ajax *AjaxAction) SetUrl(url string) *AjaxAction {
    91  	ajax.Url = url
    92  	return ajax
    93  }
    94  
    95  func (ajax *AjaxAction) SetSuccessJS(successJS template.JS) *AjaxAction {
    96  	ajax.SuccessJS = successJS
    97  	return ajax
    98  }
    99  
   100  func (ajax *AjaxAction) ChangeHTMLWhenSuccess(identify string, text ...string) *AjaxAction {
   101  	data := template.JS("data.data")
   102  	if len(text) > 0 {
   103  		if len(text[0]) > 5 && text[0][:5] == "data." {
   104  			data = template.JS(text[0])
   105  		} else {
   106  			data = `"` + template.JS(text[0]) + `"`
   107  		}
   108  	}
   109  	selector := template.JS(identify)
   110  	if !strings.Contains(identify, "$") {
   111  		selector = `$("` + template.JS(identify) + `")`
   112  	}
   113  	ajax.SuccessJS = `
   114  	if (data.code === 0) {
   115  		if (` + selector + `.is("input")) {
   116  			` + selector + `.val(` + data + `);
   117  		} else if (` + selector + `.is("select")) {
   118  			` + selector + `.val(` + data + `);
   119  		} else {
   120  			` + selector + `.html(` + data + `);
   121  		}
   122  	} else {
   123  		swal(data.msg, '', 'error');
   124  	}`
   125  	return ajax
   126  }
   127  
   128  func (ajax *AjaxAction) SetEvent(event Event) *AjaxAction {
   129  	ajax.Event = event
   130  	return ajax
   131  }
   132  
   133  func (ajax *AjaxAction) SetErrorJS(errorJS template.JS) *AjaxAction {
   134  	ajax.ErrorJS = errorJS
   135  	return ajax
   136  }
   137  
   138  func (ajax *AjaxAction) SetParameterJS(parameterJS template.JS) *AjaxAction {
   139  	ajax.ParameterJS += parameterJS
   140  	return ajax
   141  }
   142  
   143  func (ajax *AjaxAction) SetMethod(method string) *AjaxAction {
   144  	ajax.Method = method
   145  	return ajax
   146  }
   147  
   148  func (ajax *AjaxAction) GetCallbacks() context.Node {
   149  	return context.Node{
   150  		Path:     ajax.Url,
   151  		Method:   ajax.Method,
   152  		Handlers: ajax.Handlers,
   153  		Value:    map[string]interface{}{constant.ContextNodeNeedAuth: 1},
   154  	}
   155  }
   156  
   157  func (ajax *AjaxAction) Js() template.JS {
   158  
   159  	ajaxStatement := `$.ajax({
   160                              method: '` + ajax.Method + `',
   161                              url: "` + ajax.Url + `",
   162                              data: data,
   163                              success: function (data) { 
   164                                  ` + string(ajax.SuccessJS) + `
   165                              },
   166  							error: function (data) {
   167  								` + string(ajax.ErrorJS) + `
   168  							},
   169                          });`
   170  
   171  	if ajax.Alert {
   172  		b, _ := json.Marshal(ajax.AlertData)
   173  		ajaxStatement = "swal(" + string(b) + `,
   174                      function () {
   175  						` + ajaxStatement + `
   176  					});`
   177  	}
   178  
   179  	return template.JS(`$('`+ajax.BtnId+`').on('`+string(ajax.Event)+`', function (event) {
   180  						let data = `+ajax.Data.JSON()+`;
   181  						`) + ajax.ParameterJS + template.JS(`
   182  						let id = $(this).attr("data-id");
   183  						if (id && id !== "") {
   184  							data["id"] = id;
   185  						}
   186  						`+ajaxStatement+`
   187              		});`)
   188  }
   189  
   190  func (ajax *AjaxAction) BtnAttribute() template.HTML { return template.HTML(`href="javascript:;"`) }