简体   繁体   中英

Send Default data through ajax post request

I am trying to send a default data in every ajax post request however using the below code I the data is being sent for all the requests. Please suggest.

$.ajaxSetup({
          data: {
             at: $('#at').attr('value'),
          },
       });

I think you can try below. Thought not tried it running.

  1. Setup the ajax like below with "beforeSetup"

     $.ajaxSetup({ beforeSend: myFunc }); 
  2. In the function "myFunc" check if it is a post request then set the data.

UPDATE : This will work !

$.ajaxSetup({
                  beforeSend: function(xhr, settings) {
                          if (settings.type == 'POST') {
                                  if(settings.data == null || settings.data == '' || settings.data == undefined) {
                                          settings.data = "?value=test";
                                  } else {
                                          settings.data = settings.data + "&value=test";
                                  }
                          }
                  }
               });

You can register a global AJAX event handler like .ajaxSend() and check the request type, for example

$(document).ajaxSend(function(event, jqxhr, settings) {
    if (settings.type == 'POST' && !settings.data) {
        settings.data = $.param({at: $('#at').attr('value')});
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM