dimanche 26 juin 2016

Using AJAX (as RESTful API) in Node.js to GET a JSON file and parse it based on which button in the front end is clicked

I'm having a lot of trouble understanding how to communicate between server.js (Node.js) and the front end javascript file. I need to use AJAX as a RESTful API in the server to get a JSON file and parse it based on certain buttons in my front end html file. I then need to send the parsed JSON back to my front end javascript file to be stylized and put into html elements for display.

I understand how to get the JSON file in the server, but I'm confused about how to tell which button was clicked (I've read that I can't use $("button").click in the server file) and how to send the parsed JSON back to my front end javascript file to be stylized into html elements.

my code:

right now I have the RESTful API stuff in the front end javascript file, which isn't where it's supposed to be..I haven't changed it yet as I have no idea how to communicate between the two files as I've stated above and don't want to change anything without some idea of how to do that.

server side code:

var http = require('http');

var fs = require('fs');

var path = require('path');

var types = {

    '.js' : 'text/javascript',

    '.html' : 'text/html',

    '.css' : 'text/css'

};



var server = http.createServer(function(req, res) {

    var lookup = path.basename(decodeURI(req.url)) || 'a3.html';

    var f = 'content/' + lookup;

    fs.exists(f, function(exists) {

        if (exists) {

            fs.readFile(f, function(err, data) {

                if (err) {

                    res.writeHead(500);

                    res.end('Error');

                    return;

                }

                var headers = {'Content-type': types[path.extname(lookup)]};

                var s = fs.createReadStream(f).once('open', function() {

                    res.writeHead(200, headers);

                    this.pipe(res);

                });

            });

            return;

        }

        res.writeHead(404);

        res.end();

    });

});

server.listen(8080);

console.log('Server running at http://127.0.0.1:8080/');

client side javascript (only the first two buttons just to get an idea): $(document).ready(function() { $("button#arts").click(function() { $.ajax( { url: "./nytimes.json", method: "GET", dataType: "json" }).done(function(json) { for (var i = 0; i < json.num_results; i++) { var $text = $("

").text(json.results[i].published_date + "
" + json.results[i].title + //"
" + obj.results[i].abstract + "
" + json.results[i].short_url + "
"; $("section").append($text); } }).fail(function(jqXHR, textStatus) { alert("Request failed: " + textStatus); }); });
    $("button#aut").click(function() {
        $.ajax(
        {
            url: "./nytimes.json",
            method: "GET",
            dataType: "json"
        }).done(function(json) {
            for (var i = 0; i < json.num_results; i++) {
                var authors = JSON.stringify(json.results[i].byline);
                var names = authors.slice(3);
                var singlename = authors.split("and");
                var $list = $("<ul></ul>");
                $("section").append($list);
                if (singlename.length == 1) {
                    var $text = $("<li></li>").text(singlename);
                    $("ul").append($text);
                } else if (singlename.length == 2) {
                    var $text = $("<li></li>").text(singlename[0]);
                    var $texttwo = $("<li></li>").text(singlename[1]);
                    $("ul").append($text);
                    $("ul").append($texttwo);
                }
            }
        }).fail(function(jqXHR, textStatus) {
            alert("Request failed: " + textStatus);
        });
    });
});

and client side html file:

<!DOCTYPE html>

<html>





    <head>

        <title></title>

        <link rel="stylesheet" type="text/css" href="content/style.css">
        <script type="text/javascript" src="content/jquery-2.2.4.min.js" defer></script>
        <script type="text/javascript" src="content/script.js" defer></script>

    </head>

    <body>

        <ul>

            <li>Click the "View Articles" button to view the basic information on all articles.</li>

            <li>Click the "View Authors" button to view all known authors.</li>

            <li>Click the "View URLs" button to view short URLs for all articles.</li>

            <li>Click the "View Tags" button to view all tags connected to articles; tags 

                are sized from largest to smallest based on tags with the most and least 

                articles, respectively. 

            </li>

            <li>To view a specific article, enter the article number (beginning with 0) in 

                the "Article Number" field and click the "Find" button. 

            </li>

            <li>Click the "View Media" button to view all articles as hyperlinked images or video</li>

        </ul>

        <button id="arts">View Articles</button>

        <button id="aut">View Authors</button>

        <button id="url">View URLs</button>

        <button id="tag">View Tags</button>

        <form method="post" action="/">

            Article Number: <input id="entry" type="text" name="ArtNum" value="">

            <input id="art" type="submit" value="Find">

        </form>

        <button id="hyper">View Media</button>
        <section id="data"></section>

    </body>

</html> 

Aucun commentaire:

Enregistrer un commentaire