开发者

Getting JSON encoded variables from php

i have this php code:

$query = mysql_query("SELECT * FROM table WHERE id=$id");
while($item = mysql_fetch_assoc($query)){
    $dataArray['var1'] = $item['var1'];
    $dataArray['var2'] = $item['var2'];
    $dataArray['var3'] = $item['var3'];
    array_push($return_arr,$dataArray);
}

echo json_encode($return_arr);

it's in my ajax.php file

Then I'm using jquery to send there id via ajax request:

$.ajax({
    type: "POST",
    url: 'ajax.php',
    data: 'id='+id,
    success: function(data) { 
      开发者_运维百科  alert(data);
    }
 });

and it alerts me this: [{"var1":"somevarhere","var2":"somevarhere2","var3":"somevarhere3"}]

can someone tell me please how I can access for ex. var3 to get somevarhere3?

thanks


According to the documentation of jQuery.ajax, the data it receives as first parameter is interpreted depending on the value of the dataType option passed to jQuery.Ajax.

What if you pass 'json' for that parameter ?
Like this :

$.ajax({
    type: "POST",
    url: 'ajax.php',
    data: 'id='+id,
    dataType: 'json', 
    success: function(data) { 
        alert(data);
    }
 });

Doing this, jQuery.ajax should interpret the data returned from the server as JSON.


Else, the documentation says that, if no dataType is specified (quoting) :

jQuery will try to infer it based on the MIME type of the response

So, the other solution would be to return some JSON content-type from the PHP code (see The right JSON content type?), with something like this :

header('Content-type: application/json');

Before doing the echoing.

And, again, jQuery.ajax should interpret the data returned from the server as JSON.


Ok, I found the solution. Thanks to Pascal MARTIN I got the idea to parse the result so I used this:

data = data.substring(1,data.length-1);
data = $.parseJSON(data);
alert(data.var3);

first line removes [], second line parses JSON to Object, and third line accesses the property


Should be able to access it like this:

data[0].var3

Where 0 is the index of the item in the array you want to access.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜