简体   繁体   中英

How to set jquery ajax headers authorization based on url?

I have a wordpress website that has woocommerce ajax requests on its Order Page. The website has a staging domain and a live domain.

$(function(){
   var root_url = 'https://'+window.location.hostname;
   console.log(root_url);
});

Ajax Request sample for staging:

$.ajax({
  type: 'GET',
  url: https://staging-mywebsite.net/wp-json/wc/v2/products?category=504,
  cache: false,
  beforeSend: function(jqXHR, settings) {
  },
  headers: {"Authorization": "Basic " + btoa("ck_123" + ":" + "cs_123") // staging},
  success: function(data) {
  }
});

Ajax Request sample for Live site:

$.ajax({
  type: 'GET',
  url: https://livewebsite.com/wp-json/wc/v2/products?category=504,
  cache: false,
  beforeSend: function(jqXHR, settings) {
  },
  headers: {"Authorization": "Basic " + btoa("ck_456" + ":" + "cs_456") // staging},
  success: function(data) {
  }
});

The live and staging website has different username and password on the headers property.

Do you know how can I set a condition or a global variable for the headers property depending on the domain?

Any help is appreciated. Thanks

Have you tried using the document.domain property? I'm thinking something like this:

var headers = {"Authorization": "Basic " + btoa("ck_456" + ":" + "cs_456")} // Assume live site
if( document.domain === "staging-mywebsite.net" ){
  headers = {"Authorization": "Basic " + btoa("ck_123" + ":" + "cs_123")} // Use staging instead
}

And then inside your AJAX request you use the variable instead.

...
headers: headers,
...

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