简体   繁体   中英

Call a GET API each XX seconds, and put the JSON response in a CSV

I'm a newbie, and I apologize for this. I am writing a script that will make a GET request. The result is a JSON array and the best deal would be to have it put automatically in a CSV/TXT file.

$.ajax({
type: "GET",
url: BASE_URL,
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(jimmi) {
// Output the results
if (typeof jimmi === "string") {
station = JSON.parse(jimmi);
}             
var ar_len = jimmi.length
for (i=0; i < ar_len;) {
$("#results").html(
"Station: " + jimmi[i].name + "<br />")  
i++     
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});

My problems: * I get displayed only the last element of the array, and I can't figure out why. * I would need to make this call automatically each 5 seconds * The JSON results should be written into a CSV/TXT file.

Can someone help me? BTW, the URL is https://its.navizon.com/api/v1/sites/1001/stations/ and you can log using demo@navizon.com - no password (read only)

Your problem is that you're changing the contents of #results for each element of jimmi by changing the entire inner HTML. So in the end, only the last element gets displayed. You need to use append instead. To make the call every 5 seconds, use the setTimeout method. Something this like:

function makeCall() {
    $.ajax({
        type: "GET",
        url: BASE_URL,
        beforeSend: function(jqXHR) {
        jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
        },
        success: function(jimmi) {
            // Output the results
            if (typeof jimmi === "string") {
                jimmi = JSON.parse(jimmi);
            }

            for (i=0; i < jimmi.length; i++) {
                $("#results").append("Station: " + jimmi[i].name + "<br />");
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('Error');
        }
    });

    window.setTimeout(makeCall, 5000);
}

makeCall();

Note: The line station = JSON.parse(jimmi); is not useful because the variable station is never used. I changed it to something that made more sense.

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