2021年3月3日水曜日

fetch() Ajax

// XMLHttpRequest()
function F_httprequest() {
    let req = new XMLHttpRequest();
    let url = '/' + CSVFile + '?key=' + Math.floor(Math.random() * (1 - 100) + 100);
    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            let ajaxText = req.responseText;
            F_create_master(ajaxText);
            F_read_ajax(ajaxText);
        }
    }
    req.open("GET", url, true);
    req.send(null);
}

// fetch()
async function testFetch() {
    let pim = fetch('/' + CSVFile + '?key=' + Math.floor(Math.random() * (1 - 100) + 100));
    pim.then(function (msg) {
        msg.text().then(function (ajaxText) {
            console.log(TAGLine, 'step1');
            F_create_master(ajaxText);
            F_read_ajax(ajaxText);
        }).then(function () {
            console.log(TAGLine, 'step2');
        }).catch(function () {
            console.log(TAGLine, 'catch');
        })
    }).catch(function (e) {
        console.log(TAGLine, 'URLerror');
        console.log(e);
    })
}

// fetch() async await
async function testFetch() {
    let url = '/' + CSVFile + '?key=' + Math.floor(Math.random() * (1 - 100) + 100);
    let opt = {
        method: 'GET',
        headers: {
            // "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        },
        // body: 'key=8080',
    };
    try {
        let pri = await fetch(url, opt);
        pri.headers.forEach(function (value, key) {
            console.log(key, value);
            // content - length 20949
            // content-type text/csv
            // date Fri, 05 Mar 2021 17:36:09 GMT
            // last-modified Fri, 05 Mar 2021 16:02:52 GMT
            // server SimpleHTTP/0.6 Python/3.9.0
        })
        let csvt = await pri.text();
        F_create_master(csvt);
        F_read_ajax(csvt);
    } catch (error) {
        console.log('error');
    }
}

0 件のコメント: