kaymeezy
kaymeezy

Reputation: 45

Make a Javascript array into JSON

I've tried searching google and nothing is clear, plus you guys are way faster and correct.

I have an array as follows:

var bannertext = new Array();
bannertext[1] = "ladidadi";
bannertext[2] = "blahblahblahblah";
bannertext[3] = "oooaaaaooooaaa";

How do I turn the bannertext array into a JSON encoded array so that I can send it to a PHP page and break it down using the json_decode function, and then how do I access the individual variables?

EDIT: Thanks to Gazler for that first part! My PHP page looks like this:

$bannertext = $_GET['bannertext'];
$banner = json_decode($bannertext);

How do I access each of those strings now? LIke echo $banner[1]; and so on?

Upvotes: 1

Views: 96

Answers (2)

Gazler
Gazler

Reputation: 84150

You use JSON.stringify() however in IE you will need to include the json2 library as IE has no native JSON parsing.

var bannertext = new Array();
bannertext[1] = "ladidadi";
bannertext[2] = "blahblahblahblah";
bannertext[3] = "oooaaaaooooaaa";
console.log(JSON.stringify(bannertext));

As an aside, you can instantiate an array using the array literal syntax.

var bannertext = [];

Here is a blog post explaining the difference.

Upvotes: 2

Joe
Joe

Reputation: 82614

JSON.stringify:

JSON.stringify(bannertext);

Older browsers, IE7 and below, require an external library Json2 Free CDN

Upvotes: 1

Related Questions