简体   繁体   中英

Why is AJAX GET request only working once?

I am trying to run a script to switch some electrical plugs on a WebApp and it works perfect but here comes the problem it only works once and I can't figure out why. I've also recognized that there is an XHR request going on forever without receiving a response as soon as I call the function.

Here is the function on my node JS server and on my Web App:

 function ajaxChangePlug(num,state) {
                $.ajax({
                    url: `/api/${num}/${state}`,
                    type: "GET",
                    data: { 
                        state: state,
                        num: num
                    },
                    dataType: "json",
                })
            };
        function handle1(num,state){
                ajaxChangePlug(num,state);
                if (state === "on") {
                    document.getElementById("1").setAttribute( "onClick", `handle1(${num},'off')`);
                    document.getElementById("1").src=`/resources/${num}_on.png`
                } else {
                    document.getElementById("1").setAttribute( "onClick", `handle1(${num},'on')`);
                    document.getElementById("1").src=`/resources/${num}.png`
                }    
            };
server.get('/api/:num/:state', (req, res) => {
    var state = req.params.state;
    var num = req.params.num;
    if(state === 'on'){
        shell.exec(`/home/pi/mynode/${num}${state}_on.sh`);

    }else{
        shell.exec(`/home/pi/mynode/${num}${state}_off.sh`);        
    }
});

You should wait for the response in you front-end like this:

 $.ajax({ url: `/api/${num}/${state}`, type: "GET", data: { state: state, num: num }, dataType: "json", success: function (data) { if (data.state === "on") { document.getElementById("1").setAttribute("onClick", `handle1(${num},'off')`); document.getElementById("1").src = `/resources/${num}_on.png` } else { document.getElementById("1").setAttribute("onClick", `handle1(${num},'on')`); document.getElementById("1").src = `/resources/${num}.png` } } })

In your backend you should send the response like this:

 server.get('/api/:num/:state', (req, res) => { var state = req.params.state; var num = req.params.num; if (state === 'on') { shell.exec(`/home/pi/mynode/${num}${state}_on.sh`); res.send('on'); } else { shell.exec(`/home/pi/mynode/${num}${state}_off.sh`); res.send('off') } });

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