0

My server (node.js) maintains an array :

var list = [];

I want to use this array in some js code (client side). I would like to retrieve it thanks to ajax. What is the best practice?

$.ajax({
    url: "http://localhost:8000/updatePendingAlerts",
    timeout: 2000,
    success: function (data)  {
      console.log(data);
      //data should be an array

    },
    error: function(jqXHR, textStatus, errorThrown) {
      clearInterval(timeout);
      alert('error ' + textStatus + " " + errorThrown);
    }
  });
4
  • In express you could do res.send(JSON.stringify(list)); Commented Apr 21, 2015 at 15:52
  • is this the best practice thought? Commented Apr 21, 2015 at 15:53
  • Check there : stackoverflow.com/questions/20881213/… Commented Apr 21, 2015 at 15:56
  • Set headers as mentioned in Quetin's answer and then i think it is Commented Apr 21, 2015 at 15:56

1 Answer 1

3

Serialise it to JSON (with JSON.stringify) and output it with an application/json content-type header.

It will then be an array in data with the client side JavaScript you already have.

Sign up to request clarification or add additional context in comments.

2 Comments

thank that worked. I was just wondering if had no other options then using json.
There are lots of options. JSON is just simplest and easiest since JS speaks it natively and it maps directly onto JS data types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.