Ok. I need help with this. For some reason the onreadystatechange is fired multiple times. I really need to get this figured out tonight. It's the last task I have left and I don't know what to do or what's causing it. Please help.
I'm using AJAX (ndhr) to send over JSON 'Y-m-d h:i:s' to PHP to use the strtotime() function to return 'm-d-Y' back through AJAX. The JSON and PHP work great, but when the onreadystatechange is fired it does it multiple times. Almost like the readyState == 4 more times than it does.
var divs_d = ["d_2009", "d_2010", "d_2011"];
function ajax_get_json(cdiv,ocdv,ed){
var hr = new XMLHttpRequest();
hr.open("GET", "/json/sample.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
cdiv.innerHTML = "";
var data = JSON.parse(hr.responseText);
var cad = data.comm_archive;
var rndate;
var nda = new Array();
var ndac = 0;
var ec = 0;
for (ni = 0; ni < cad.length; ni++) {
if (cad[ni].year == ocdv) {
ec = ec + 1;
ed.innerHTML = '<h4>' + ocdv + ' (' + ec + ' entries)</h4>';
var ndhr = new XMLHttpRequest();
var url = "/inc/strtotime.php";
var vars = "ndate=" + cad[ni].publish_date;
ndhr.open("POST", url, true);
ndhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ndhr.onreadystatechange = function () {
if (ndhr.readyState == 4 && ndhr.status == 200) {
nda[ndac] = ndhr.responseText;
ndac = ndac + 1;
}
}
ndhr.send(vars);
}
}
nda.sort(function (a, b) { return b - a });
for (ndai = 0; ndai < ndac; ndai++) {
cdiv.innerHTML += '<h4><a href="/this_is_a_Test/archive.php?cdate=' + nda[ndai] + '">' + nda[ndai] + '</a></h4>';
}
}
}
hr.send(null);
}
function optionCchange() {
var ocdv = document.getElementById("optionCdate").value;
var ed = document.getElementById("ediv");
for (i = 0; i < divs_d.length; i++) {
var cdiv = document.getElementById(divs_d[i]);
if (divs_d[i] == "d_" + ocdv) {
cdiv.className = "bddiv show";
ajax_get_json(cdiv,ocdv,ed);
} else {
cdiv.className = "bddiv hide";
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…