I have a php array with key, value pairs. I have json encoded it. And using ajax.Request i called the php file in which that array is there. Now i have to access both key and valu开发者_StackOverflow社区e pairs. Could anyone let me know how to do that?
You need to parse the JSON.
- You can use the JSON library.
- You can use a library method like jQuery's
$.parseJSON()
. - If the JSON is trusted, you can use
eval()
.
Code in javascript "json.js" is required. you can download this.
var votedCommentString = getCookie("votedComment"); // get value of voted comment cookie
votedComment = JSON.parse(votedCommentString); // extract json object into array
votedComment[votedComment.length] = id; // add more data in array
var cookieData = JSON.stringify(votedComment); // convert array into json object
setCookie("votedComment", cookieData, 365); // and again set cookie
In PHP you can access this in following way
$cookieData = (array)json_decode($_COOKIE["votedComment"]); // extract json object into array
print_r($cookieData);
Use
json_encode($array_variable) // to convert array in to json
As you said the array is in php file which is called via ajax, you can simply decode the json encoded string and retrieve the array with keys and values respectively.
Simply use json_decode() function to retrieve the array.
精彩评论