简体   繁体   中英

Javascript Array - Creating from string pulled from textbox (jquery)

I have a php script which loops through and creates a string of values (see below) this value is then added to a hidden textbox. Now what I want to do is pull this value into my javascript using jQuery and create an array.

$events contains the following values:

{date:'2014-01-29'},{date:'2014-01-30'},{date:'2014-01-31'},{date:'2014-02-01'},{date:'2014-02-03'}

Here is the textfield:

<input type="hidden" id="events" value="<?=$events?>">

Here is the line in my js file to create the array:

var eventarray=[$("#events").val()];

Now when I alert() eventarray in my js it gives me:

{date:'2014-01-29'},{date:'2014-01-30'},{date:'2014-01-31'},{date:'2014-02-01'},{date:'2014-02-03'}

but what I need it to return is (so I can use the array correctly):

[object Object],[object Object],[object Object],[object Object],[object Object]

I am trying to pass a dynamic set of dates from my db to a calendar (I'm using CLNDR).

You can use JSON.parse

var eventarray=JSON.parse('['+$("#events").val()+']');

Fiddle Demo

or in jQuery $.parseJSON()

var eventarray=$.parseJSON('['+$("#events").val()+']');

Fiddle Demo

Keep in mind that your JSON string needs to be well-formed, and that means double-quoting property names and values,hence change the $events variable as follows

{"date":"2014-01-29"},{"date":"2014-01-30"},{"date":"2014-01-31"},{"date":"2014-02-01"},{"date":"2014-02-03"}

Documentation

What you should do is amend your output so that you produce a JSON string (ie double quote the properties as well as the keys):

var json = '{"date":"2014-01-29"},{"date":"2014-01-30"},{"date":"2014-01-31"},{"date":"2014-02-01"},{"date":"2014-02-03"}';

This isn't quite proper JSON yet. You need to amend the string like so:

var str = '[' + json + ']';

Then parse it:

var arr = JSON.parse(str);

Demo

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