I have been misinterpreted. I have created a JSON Object in PHP. I just need access to that object in Javascript. That is all.
I just learned that many of my problems can be solved by using JSON. Now learning how to use JSON is another 开发者_如何学Pythonproblem, though. ;-)
Suppose this is the code in PHP:
$row = array()
while ($row = mysql_fetch_object($result)
{
$data[] = $row;
}
$javascriptFriendlyData = json_encode($data);
Now how do I access the $javascriptFriendlyData in javascript. I tried using JQuery but I can't really figure out much...
If it helps, the JSON Data structure is somewhat like this:
[{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}...
]
Try this:
<script>
<?php
echo 'var data = '.$javascriptFriendlyData;
?>
// now the JSON data is stored in the data variable
console.log(data);
</script>
I'm assuming you are running PHP in the HTML template here:
<html>
<head>
<script><?php echo 'var data = '.$javascriptFriendlyData; ?></script>
<script src="some_js_file.js"></script>
</head>
<body>
etc...
In the some_js_file.js
, you can now access the data
variable.
If it's an array of simple data as you describe, there is little reason to eval()
it, but you might consider it anyway.
From the official JSON documentation:
var myObject = eval('(' + myJSONtext + ')');
Now you can use it like any other Javascript object.
If you are creating the JSON encoded data in your PHP script and echoing in your JavaScript, you don't even have to call eval because it is already in a native JavaScript format.
So taking your code...
$row = array()
while ($row = mysql_fetch_object($result)
{
$data[] = $row;
}
$javascriptFriendlyData = json_encode($data);
Then, in your Javascript code you can do something like...
<script type="text/javascript">
var data = <?php echo $javascriptFriendlyData; ?>;
</script>
Then when the page is rendered, the data is already parsed and ready to use. It is when you are handling AJAX requests that return data that it needs to be evaluated. Otherwise, it is no different then using JavaScript notation inline.
eg:
<script type="text/javascript">
var somevar = [{objVar1:"SomeVal"},{objVal2:"SomeVal2"}];
</script>
If you are trying to have your JavaScript in a separate file, then you will need to set this variable in your JavaScript before you load your JavaScript file or run the JavaScript file through the PHP interpreter.
JSON is just a notation for Javascript data. Which means you can have this kind of JS code :
var data = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
Which will just put your data in the data
Javascript variable.
Considering that []
symbolize an array, and {}
symbolize an object, you can use this to access the title
property of the first element of the data
array :
alert(data[0].atitle);
And you'll get
Ameya R. Kadam
And, to loop over each elements of the data
array, you can use something like this :
var i;
for (i=0 ; i<data.length ; i++) {
alert(data[i].aid + ' : ' + data[i].atitle);
}
(Absolutly no need for jQuery for such a task, btw)
If your array is in a variable called data
:
$.each(data, function(){
alert(this.aid);
alert(this.atitle);
});
var arr = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
$.each(arr, function() {
alert(this.aid)
alert(this.atitle)
})
Or
var arr = [{"aid":"1","atitle":"Ameya R. Kadam"},{"aid":"2","atitle":"Amritpal Singh"}];
$.each(arr, function(i,o) {
alert(o.aid)
alert(o.atitle)
})
I have found that the JSON.org Json2.js library to come in handy for going from JSON to JS and back from JS object to JSON. For example, instead of:
var obj = eval('(' + jsonString + ')');
with the JSON.org library you use:
var obj = JSON.parse(jsonString);
You can also specify a second parameter that allows you to work with the results of the JSON being revived as an object.
To go back to a JSON string just call:
var jsonString = JSON.stringify(obj);
This also takes optional arguments to help control JSON string creation.
JSON basicalle represents a Data Structure right, so essentially it's an Object, or instance of a Class, so to use it you do this:
var MyJSonObject = eval("(" + jSonString + ")");
UPDATE
hey Amit, you can't access PHP objects from javascript. What you have to do is somehow construct the JSON string in PHP, but then write it out to the client. I'm not sure how you'd do it in PHP, but this how you'd do it in ASP. The idea is the same, the syntax will be different in PHP.
<html>
<head>
<script type="text/javascript">
var MyObject = eval("(" + <%= Response.Write(strServerSideVariable) %> + ")");
</script>
</head>
<body>
</body>
</html>
Note that in ASP/.NET the tags "<% %>" denote server side, not client side, code. This is what you have to do with PHP amit
It's worth noting that some browsers now provide a set of native functions for JSON decoding and encoding: JSON.parse() and JSON.stringify(). They are safer than using the eval() function and only works if the JSON data is well-formed, whereas eval() would evaluate things like the following:
{
'hello': (undefined
? 'world'
: ('number ' + Math.floor (40.235)))
}
What's wrong with that? The JavaScript value `undefined' is not available in JSON (only true, false, null, strings and numbers are allowed); single quotes are used everywhere when only double quotes are valid in JSON; you can't call JavaScript functions or perform string concatenation in JSON.
Obviously the last one is a big problem because you could receive some malicious JSON, possibly a value from a form input, that attempts to tamper with things. So when possible, use JSON.parse() and JSON.stringify()...because eval() is dangerous.
Edit:
I misread the original post. If you have a JSON object in PHP and you want to use it in JavaScript, you would need to convert the JSON object to a string and pass it on to JavaScript. The only way to do that would be to make your JavaScript code actually ask for the newly created JSON string in the first place. PHP would return a string, JavaScript would use eval() or JSON.parse() on the string, and you'd have your object in JavaScript. I'm not sure if there is a non-AJAX way to do this without making your JavaScript files into PHP files, setting the Content-Type header, etc., but I know that AJAX would work in this situation.
精彩评论