繁体   English   中英

jQuery。$ ajax内容仅在刷新(F5)之后加载

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

在外部服务器上,有一个包含一些.html文件的文件夹,其中一个是index.html。

服务器可以在URL中同时加载:foldername或foldername / index.html。 在每个html文件中,我加载一个js文件。 现在的问题是,来自我服务器的远程json文件位于{filename} .json。 这个概念很好用,但是当我第一次只加载没有index.html的文件夹名时,似乎没有使用index.json文件。

刷新页面(F5)或使用激活的开发人员工具第一次打开页面后,查看console.log,它会按预期工作。 这已通过google chrome和FF测试。

以下是相关代码:

//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);

将以上所有代码放入函数中:

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

并调用myCode(); 每当您希望它运行时。 单击某些内容时,您可能希望运行它,例如:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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