First I have my data encoded in the json_encode function.
Looks like this for example:
{\"test\":\"test value\"}
What I want to do is m
index.php (use json_encode
here):
<?php
$foo = array('test' => 'test value');
echo json_encode($foo);
?>
example.html
<script type="text/javascript">
$.get('index.php', function(response) {
alert(response['test']);
// this will alert "test value"
}, 'json');
</script>
EDIT1: example.html (without-jQuery solution):
<script type="text/javascript">
window.onload = function() {
var request;
request = getHTTPObject();
request.onreadystatechange = sendData;
request.open("GET", "index.php", true);
request.send(null);
}
function sendData() {
if(request.readyState == 4){
var JSONtext = request.responseText;
var JSONobject = JSON.parse(JSONtext);
// notice how variables are used
var output = JSONobject.test;
alert(output); // displays "test value"
}
function getHTTPObject(){
var xmlhttp = false;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
</script>
Objects are associative arrays. They store key/values pairs. So All you have to do is:
var test = function(){}
test["hello"] = "world";
This will set hello
as a variable and world
as its value.
you can test this by doing
alert(test.hello);
Replace hello
and world
with the json key and value
Hope this help more with this example: I am using Jquery AJAX to go to index.php resource and return a json object.
index.php
<?php
$variables = array('hello' => 'world');
echo json_encode($variables);
?>
example.html
var test = function(){}
$.ajax({
url: index.php,
success: function(json) {
for(var key in json ){
var testVarName = key;
var testVarValue = json[key];
test[testVarName ] = testVarValue;
}
}
});
So now test
object has variable hello
and it value is world
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
straight from the jquery docs...