简体   繁体   中英

Can't figure out how to get a response from an ajax call

I have this code:

render() {
    var urlstr : string = 'http://localhost:8081/dashboard2/sustain-master/resources/data/search_energy_performance_by_region.php';
    urlstr = urlstr + "?division=sdsdfdsf";
    urlstr = urlstr + "&region=sfdsf";
    urlstr = urlstr + "&date_from=sfdsf";
    urlstr = urlstr + "&date_to=sfdsf";
    urlstr = urlstr + "&sq_from=sfdsf";
    urlstr = urlstr + "&sq_to=sfsd";

    console.log("--------------------------");

    fetch(urlstr)
        .then(response => {
            console.log("==================================");
            console.log(response);

            if(!response.ok){
                (document.getElementById('result_div') as HTMLInputElement).innerHTML = 'error';
                console.log("error");
            }else{
                (document.getElementById('result_div') as HTMLInputElement).innerHTML = 'ok';
                console.log("ok");
            }
        });

    console.log("--------------------------");

    return(
        <div id='result_div'>
            test
        </div>
    )
}

Please pardon the console.log lines, that is me trying to track this problem.

But when that page is called on Node, it ought to make a call to a remote server (In this case an apache server running on my local machine that runs a select against a DB and returns a JSON object), then return the "test" string to the browser as the page. Then when the stuff is done running, it ought to put either error or ok in that result_div.

I know for a fact that the call to the php page is running - I can do a show processlist on that server and see the select executing. But the problem is that the typescript code never seems to actually do the call back stuff when it is done sending the data back.

What am I doing wrong?

Aren't you forgetting to call .json() on the response first?

    fetch(urlstr)
        .then(response => {
            if(!response.ok) {
                (document.getElementById('result_div') as HTMLInputElement).innerHTML = 'error';
                console.log("error");
            } else {
                (document.getElementById('result_div') as HTMLInputElement).innerHTML = 'ok';
                console.log("ok");
            }
            return response.json();
        })
        .then(data => {
            console.log(data);
        });

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