简体   繁体   中英

Append to list ajax result in nodejs

I have server.js and it is already connected to mysql and main page is index.html and I put html code.

I want show ajax result to li element but

var cooloo=res.end(JSON.stringify(data));
window.document.getElementById('resultlist').innerHTML += cooloo;

Is not working in nodejs. Current ajax result code is below

app.get('/search',function(req,res){
connection.query('SELECT first_name from user_name where first_name like "%'+req.query.key+'%"', function(err, rows, fields) {
      if (err) throw err;
    var data=[];
    for(i=0;i<rows.length;i++)
      {
        data.push(rows[i].first_name);
      }
      res.end(JSON.stringify(data));
    });
});

You can't handle your front-end using your nodeJS API. Actually you can do it and there are Modules for that also but I dont think you want to use it what you want is your API is returning array right? and you want to append it to your HTML? then you can use the jquery to make the ajax call. Now what is ajax call.

Ajax call means calling an API while your page will be the same. What I mean is let me give you an example suppose you are submitting a form then when you click submit the call the API take the response and tell you that some message success or error this is not ajax call yes it can be ajax call but if it will change your URL state and all the stuff then it's not ajax call you may have seen sometimes while sign up when you enter username they show "This username Already used" This is ajax call as they are calling the API getting the result and priting it on the same page.

So, lets use jquery for your doubt. If you havent added the jquery then add this link iin your head in index.html

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>

then use this in your body

<script>
$.ajax({ 
    type: "GET",
    dataType: "json",
    url: "http://localhost:8080/search",
    success: function(data){        
        $('#resultlist li').each(function (index) {
            $(this).text(names[index]);
        });
    }
});
</script>

and send object directly from response I mean currently you are converting it to string there is no need. Hopefully this will help.

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