简体   繁体   中英

node.js parse array from jquery ajax

I'm creating an application in node which will get the array sent from jquery Ajax, here is my code:

Ember.$.ajax
({
  type:"PUT",
  url:"http://localhost:3000/ids/",
  data:
  {
    ids:[29,12,43],
  },
    dataType: 'json',
});

Here is my node.js code:

router.put('/ids/', function(req, res) 
{
  var data = req.body;
  console.log(data);
  console.log(data.ids);
});

The result is:

{ 'ids[]': [ '29', '12', '43' ] }
undefined

I've also tried to iterate over it, but the code:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    console.log(key + " -> " + data[key]);
  }
}

Is not working also. What can I do in that case?

The 'ids[]:' does not look like the correct format for a key in JSON - are you sure this is what the console is printing? In any case, if the data you are receiving is coming in as a string (even when the string looks like JSON ) - you could try and parse it into JSON object. Here is an example for your case:

router.put('/ids/', function(req, res) 
{
  var data = req.body;
  //if the string is a properly formatted JSON, this should pass:
  var dataJSON = JSON.parse(data);
  console.log(data);
  //then see if this gives you what you expect
  console.log(dataJSON);
  console.log(dataJSON.ids);
});

Give it a try and let me know if this helps.

UPDATE: Seeing that the data you receive is not a well-formatted JSON, try changing the PUT request into something like this:

Ember.$.ajax
({
  type:"PUT",
  url:"http://localhost:3000/ids/",
  data: JSON.stringify({'ids':[29,12,43]}), 
  dataType: 'json',
});

Give it a try and let us know what the console is printing on the server and if the problem persists.

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