how to pass headers in jQuery.load like ajax?

12,589

Solution 1

You can use beforeSend option in jquery ajax , like as follows :

$.ajax({
    url: "http://localhost/restTest",
    data: { uname: "asdf" },
    type: "GET",
    beforeSend: function(xhr){xhr.setRequestHeader('X-TOKEN', 'xxxxx');},
    success: function() { alert('Success!' + authHeader); }
});

or can also use headers like,

$.ajax({
    url: "http://localhost/restTest",
    data: { uname: "asdf" },
    type: "GET",
    headers:{ "X-TOKEN": 'xxxxx'},
    success: function() { alert('Success!' + authHeader); }
});

Solution 2

You can not pass headers data to $.load() , but you can set default setup using $.ajaxSetup() like this :

$.ajaxSetup({
    'headers':{
        'header1':'value1',
        'header2':'value2',
    }
}
);

//give the load call here
$('selector').load('url',function(){
    //do things
})

Disclaimer From jquery doc:

Its use is not recommended.

The best way is do the is thing using $.ajax() :

$.ajax({
  url: "test.html",
  headers : {header1 : "header1"}       
  }).done(function(data) {
     $('selector').html(data);
});
Share:
12,589

Related videos on Youtube

Rocky Andra
Author by

Rocky Andra

Updated on June 16, 2022

Comments

  • Rocky Andra
    Rocky Andra about 2 years

    I've been stuck from this issue in couple of days. I want to send some headers data in jQuery.load(). It seems that jQuery.load never send the headers, like ajax. Can somebody explain how to, or Is it necessary? Btw, sory my bad English.

    This is the syntax :

    $loadingBay.load(href, settings.data, function (data, status) {
        prep(status === 'error' ? $tag(div, 'Error').html(settings.xhrError) : $(this).contents());
    });
    

    Many Thanks

    • Jai
      Jai over 10 years
      What is the issue with $.ajax() is this can't do the job you want to do with .load()?
    • Royi Namir
      Royi Namir
      I think you need to use the plain ajax function. ($.ajax)

Related