2016-06-25 3 views
1

Ich habe viel Mühe zu verstehen, wie man zwischen server.js (Node) kommuniziert .js) und die Frontend-Javascript-Datei. Ich muss AJAX als eine RESTful-API auf dem Server verwenden, um eine JSON-Datei zu erhalten und sie basierend auf bestimmten Schaltflächen in meiner HTML-Frontend-Datei zu parsen. Ich muss dann die geparste JSON zurück zu meiner Front-End-Javascript-Datei senden, um stilisiert und in HTML-Elemente zur Anzeige gebracht werden.Verwenden von AJAX (als RESTful API) in Node.js, um eine JSON-Datei abzurufen und zu analysieren, basierend auf welcher Schaltfläche im Frontend geklickt wird

Ich verstehe, wie man die JSON - Datei auf dem Server bekommt, aber ich bin verwirrt, wie man sagt, auf welche Taste geklickt wurde (ich habe gelesen, dass ich $ ("button") nicht benutzen kann Server-Datei) und wie man das geparste JSON zurück an meine Front-End-Javascript-Datei sendet, um es in HTML-Elemente zu stilisieren.

mein Code:

jetzt ich die RESTful API Sachen im Frontend habe JavaScript-Datei, die nicht ist, wo es zu be..I angenommen hat, hat es noch nicht geändert, da ich keine Ahnung, wie zwischen den beiden Dateien zu kommunizieren, wie ich oben gesagt habe und nichts ändern wollen ohne eine Idee, wie das geht.

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-Seite Javascript (nur die ersten beiden Tasten nur eine Vorstellung zu bekommen):

$(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 = $("<p></p>").text(json.results[i].published_date + 
               "<br>" + json.results[i].title + 
               //"<br>" + obj.results[i].abstract + 
               "<br>" + json.results[i].short_url + "<br>"; 
       $("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); 
     }); 
    }); 
}); 

und Client-Seite HTML-Datei:

<!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> 

Antwort

0
$(document).on("click", ".arts", function() { 
    var cursor = $(this); 
    $.ajax({ 
     url: "./nytimes.json", 
     type: "POST", 
     dataType: "json", 
     data: { 
      buttonClicked:'arts' // send info to server 
     }, 
     cache: false, 
     timeout: 5000, 
     complete: function() { 
      console.log('complete'); 
     }, 
     success: function(data) { 
     // data received from the server, use it 

     }, 
     error: function() { 
      console.log(err); 
     } 
    }); 
}); 
Verwandte Themen