简体   繁体   English

无法弄清楚如何从ajax调用中获得响应

[英]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. 请原谅console.log行,这是我试图跟踪此问题。

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. 但是,当在Node上调用该页面时,它应该调用远程服务器(在这种情况下,在我的本地计算机上运行的apache服务器对数据库运行一次select,并返回JSON对象),然后返回“ test “字符串作为页面的浏览器。 Then when the stuff is done running, it ought to put either error or ok in that result_div. 然后,当这些东西完成运行时,应该在result_div中输入error或ok。

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. 我知道一个事实,即对php页面的调用正在运行-我可以在该服务器上执行show processlist,并查看select正在执行。 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? 您是否忘了先在响应上调用.json()

    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);
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM