简体   繁体   中英

jquery .$ajax content loads only after refresh(F5)

On an external server there is a folder consisting with some .html files, one of them is the index.html.

Server can load both: foldername or foldername/index.html in his url. In every html file I load a js file. Now the problem is, that the remote json file from my server exists at {filename}.json. This concept works fine but when I first load only the foldername without index.html, the index.json file seems not to be used.

After refreshing the page (F5) or open the page for the first time with activated developer tool to see the console.log it works as it should. This is tested with google chrome and FF.

Here's the relevant code:

//test if url ends with :html
var loc = window.location.pathname.split('/');
var last = loc[loc.length-1] || loc[loc.length-2];

//if not take index.json as file name
if(!last.match(/html/)){
  var file_json = "index.json";
}
else{
  var file_json = last.replace(/html/,"json");
}
var URL = base + "/" + file_json;
$.ajax({
  xhrFields: {
    withCredentials: false
  },
  type: "GET",
  url: URL
  }).done(function (data) {
  ...
  }
console.log(data);

Put all of the above code into a function:

function myCode(){
    // all the above code comes here
}

and call myCode(); whenever you want it to run. You probably will want to run it when you click something, for example:

<input type="button" value="Click me!" onclick="myCode();"/>

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