创建一个可重用的函数来打开和发送Ajax

时间:2016-06-24 12:15:23

标签: javascript ajax

我已经注意到,每当我想声明一个对象时,在我的程序中,例如list,save,add,remove我每次都会在每个函数中写下以下内容。

ajax.open("Get", "./route/action",true);     
ajax.send();

我想做这样的事情。

//this.ajax.get('./route/action').update('ajax-content');
./route/action // this is path to my Action class-using servlet

每次我必须打开连接时,请提供我的动作类的路径servlet,然后发送。我每次要加载列表,删除或更新时都这样做。

我怎样才能编写一个我将会成为的函数:

this.ajax.get('./route/action');
// 'ajax.content' is the id of the div where I 
// want to show the list,where after updating AJAX show the update list to the user.
update('ajax-content'); 

例如,在添加用户之后,我可以看到添加的用户而无需重新加载整个页面。我正在使用Java EE,Servlet和JavaScript开发maven项目。

3 个答案:

答案 0 :(得分:4)

这样做的完整代码是, 表单字段是您现在放置表单详细信息的地方

var App = App || {};

App.extend = function(proto, literal){
      var newLiteral = Object.create(proto);
      Object.keys(literal).forEach(function(k){
          newLiteral[k] = literal[k];
      })

      return newLiteral;
};

App.Cmp = {
        responseTarget: '',
        httpMethod: 'GET',
        async: true,
        httpUrl: '',
        requestParams: '',
        updateTarget: function(resp){
            document.getElementById(this.responseTarget).innerHTML = resp;
        },
        ajaxRequest: function(){
            var me = this;
            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function(){

                if(xhr.readyState == 4){
                    if(xhr.status == 200){
                        me.updateTarget(xhr.responseText);
                    }
                }
            }

            xhr.open(me.httpMethod, me.httpUrl, me.async);
            if(me.requestParams)
                xhr.send(me.requestParams);
            else
                xhr.send();
        },
        fromFields: [],
        form:  function(){
            var me = this;
            var form = '<form>';

            me.fromFields.forEach(function(el){
                form += '<div class="form-group">'
                    + '<div class="input-group">'
                    + '<div class="input-group-addon">' + el.label + '</div>';

                if(el.type == 'select' && el.options){
                    form += '<select class="form-control">';
                        el.options.forEach(function(opt){
                            form += '<option value='+ opt.value + '>' + opt.label + '</option>'
                        });
                    form += '</select>';
                }else
                    form += '  <input type="' + el.type + '" name="' 
                        + el.name + '" class="form-control" id="' + el.id + '">'

                form += '</div></div>';
            })

          form +=  '</form><a class="btn btn-success" id="' + me.formId+ '-save">Save</a>';

          me.updateTarget(form);

          document.getElementById(me.formId+ '-save').addEventListener("click", function(){
              me.submitForm();
          });
    },
    formId: '',
    formUrl: '',
    submitForm: function(){
        var me = this;

        var formValues = me.fromFields.filter(function(el){
            var formEl = document.getElementById(el.id);
            if(formEl && formEl.value)
                return el;

        }).map(function(el){
            var formEl = document.getElementById(el.id);
            return encodeURIComponent(el.name) + '=' 
                + encodeURIComponent(formEl.value);

        }).join('&');

        me.ajaxRequest.call({
            httpMethod: 'POST',
            httpUrl: me.formUrl,
            requestParams: formValues,
            responseTarget: me.responseTarget,
            updateTarget: function(resp){
            document.getElementById(me.responseTarget).innerHTML = resp;
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(params);
            }
        });

    },
    tableStore: '',
    table: function(tableUrl){
        var me = this;
        me.responseTarget = 'ajax-content';
        me.httpUrl = tableUrl;
        me.ajaxRequest();
    }
};

(function(){
    App.Cmp.table("./company/action");
})();

答案 1 :(得分:3)

  var App = App || {};//check if App is defined, if not assign
  empty
  //some inheritance here
  //pass some arguments
  App.extend = function (proto,literal){ 
  var newLiteral = Object.create(proto);//new object with the 
  specified prototype object and properties.
  Object.keys(literal).forEach(function(k){
  newLiteral[k] = literal[k];
  return newLiteral;//return some properties of the object in   a
   array
  })
  }
  //define some attributes in the created obj
  App.Cmp{
  responseTarget : '',
  httpMethod : 'GET', //can be overriden in case of POST
  httpUrl : '',
  requstParams : [],
  updateTarget : function (resp){
  document.getElementById(this.responseTarget).innerHTML = resp;
  //this refer to the new created object
  },
  ajaxRequest : function(){
  var me = this; //this refers the scoop of this function
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
  if(xhr.readyState == 4){
  if(xhr.status == 200){
  me.updateTarget(xhr.responseText);
  }
  }
  }
  xhr.open(me.httpMethod, me.httpUrl, me.async);
  //will define the method and give the url to the action
  xhr.send();
  },
  //to use it need we need to extend this.
  //have been using jsp form but can also define a form object 
  that I can extend every time I need a form.
  formFields :
  .
  .
  .
  }
  }
  //now I have something like every time I need a form,list with 
  ajax, 
  //can also add save, delete, e.t.c
  var route = App.extend(App.Cmp,{
  formFields:
  .
  .
  .
  });

答案 2 :(得分:2)

试试这个:

function ajaxRequest(AJAXurl, callbackElementID){
   x = new XMLHttpRequest(); 
   x.open("get", AJAXurl, true);
   x.onreadystatechange = function() {
    if (x.readyState == 4 && x.status == 200) {
     document.getElementById(callbackElementID).innerHTML = x.responseText; //Will send the received data to the element passed in the function
    }
  };
  x.send();
}

使用如下:

ajaxRequest("/somefile.php", "elementID"); //This will send recieved data to the element with "elementID" as id

注意:构建此方法仅适用于GET次请求。如果您想要POST请求,请更改代码。