4

i am newbie in JSON. i just started learning JSON before 30 mins.

i want to print JSON array in jquery.

 $.ajax({
                url : '/exp/resp.php',
                type : 'POST',
                dataType : 'json',
              //  data : 'uname='+uname+'&pass='+pass,
                success : function (data)
                {
                    alert(data);

                }
            });

now it's printing abc,def,ghi,jkl,mno. so i want to print it separate like abc def ghi etc.. i referred this answer but it didn't help...

Community
  • 1
  • 1
404 Not Found
  • 1,223
  • 2
  • 22
  • 31
  • 4
    `data` is not a "JSON array". Even though the response is JSON-encoded data, jQuery will have parsed the data already. So `data` is just a normal JavaScript array. The question/problem itself has nothing to do with JSON. – Felix Kling Oct 03 '13 at 06:11

3 Answers3

16

Why not print something generic like:

JSON.stringify(data);

This should work with either an object or an array.

Daryl
  • 221
  • 2
  • 5
6

if data is an array then

alert(data.join(' '));
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • tnx for answer.. i want to ask you one more thing that if i want to access it like data.1, data.2 something like this? how ot do it? i m returning it from php using json_encode($array).. – 404 Not Found Oct 03 '13 at 06:51
  • 2
    @pandit you can use the index to access it.. like `data[0]`, `data[1]`... `data[data.length - 1]` – Arun P Johny Oct 03 '13 at 06:53
  • thanks.... and one more question that if i want to send json object from php file then how send? – 404 Not Found Oct 03 '13 at 06:59
  • @pandit not sure... not a PHP guy... i think there is a `json_encode` call – Arun P Johny Oct 03 '13 at 07:08
  • @pandit Arun is right, you can convert an `array` into a json string with `json_encode` and you can convert an json string into an `array` using `json_dncode`... – zzlalani Oct 03 '13 at 07:54
2

Since your data is an array Check the following tutorial

Join the elements of an array into a string:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join();

The result of energy will be:

Banana,Orange,Apple,Mango

Have a look at this http://www.w3schools.com/jsref/jsref_join.asp

For your code use Arun P Johny's solutions

alert(data.join(' '));
Community
  • 1
  • 1
zzlalani
  • 22,960
  • 16
  • 44
  • 73
  • tnx for answer in detail.. i want to ask you one more thing that if i want to access it like data.1, data.2 something like this? how ot do it? i m returning it from php using json_encode($array).. – 404 Not Found Oct 03 '13 at 06:52