cuziluvtosmile
cuziluvtosmile

Reputation: 47

getting data from node.js server using query ajax

I am a bit confused about how to use get() and post() in query to get data from a node.js server if the node.js server parses data from a json file and serves the html at a localhost:3000, will the client side code look something like this:

$(document).ready(function() {
$.ajax({
    url: 'localhost:3000/',
    dataType: "json",
    success: function(data) {
        $("#test").append(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert('error ' + textStatus + " " + errorThrown);
    }
});
});

I am confused about what datatype etc means.

Upvotes: 0

Views: 1036

Answers (1)

Grasshopper
Grasshopper

Reputation: 1769

From jQuery documentation

dataType (default: Intelligent Guess (xml, json, script, or html)) Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

So the code you're showing expects the server to respond a json string, not HTML. If you remove dataType jQuery will 'guess' the response content as explained, which is what I believe you should do. Also the .ajax method defaults to making GET calls. If you want to POST change your code to the following - assuming you're using a jQuery version >= 1.9:

$(document).ready(function() {
  $.ajax({
      url: 'localhost:3000/',
      method: "POST",
      success: function(data) {
          $("#test").append(data);
      },
      error: function(jqXHR, textStatus, errorThrown) {
          alert('error ' + textStatus + " " + errorThrown);
      }
  });
});

You can also use jQuery's shorthand methods for GET and POST instead of the low-level .ajax method.

Upvotes: 2

Related Questions