第一,得到今天的日期,用途:
var today = new Date;
要獲得的組件,使用:
var date = today.getDate();
var month = today.getMonth() + 1; // caveat, starts at 0
var year = today.getFullYear(); // 4 numbers (e.g. 2011)
現在,你需要它的格式yymmdd
。因此,您需要從年份中刪除兩個第一個數字,並且如果需要,可以在日期和月份前添加0
。
function zeropad(number) {
var str = number.toString(); // number to string
return str.length === 1 // if length is 1
? '0' + str // prepend a 0
: str; // otherwise return string without modification
}
然後:
var formatted = year.toString().substring(2) // only the string from the first two numbers and on
+ zeropad(month) // month with 0 prepended
+ zeropad(date); // date with 0 prepended
然後,在你XHR,使用:
xhr.open("GET", "http://example.com/abc" + formatted + "-data.xml", true);
感謝您的提示。我可以按照您的建議格式化日期,但當我將「date_string」var插入到xml url時,仍然無法檢索xml數據。下面是我輸入的內容:** bold ** var url =(location.toString().indexOf('file://')!= -1)? 'http://example.com/abc'+ date_string +「-data.xml'; ** bold **然後我用** bold來調用這個var ** xmlhttp.open(GET,url,true)** bold **不知道我哪裏錯了,但它可能是一個簡單的錯誤在m語法。 – Carlos
@Carlos:使用'alert(url)'或[FireBug](http://getfirebug.com/)查看你的'url'包含的內容。順便說一句,你可以使用反引號\'在註釋中引用代碼。 – Andomar
我終於得到它的工作。我必須使用單引號而不是雙引號來插入'+ date_string +'變量......非常感謝您的幫助。這裏是我的最終代碼'code'var url =(location.toString().indexOf('file://')!= -1)的樣本? 'http://example.com/abc'+date_string+'data.xml':'fcx'+ date_string +' - data.xml'; \t xmlhttp = new XMLHttpRequest(); \t if(xmlhttp!= null){ \t \t xmlhttp.onreadystatechange = stateChange; \t \t xmlhttp.open('GET',url,true,);'code' – Carlos