how to get data in javascript passed through php mysql query
i want to display 700 products data in a select box and on per selection i have to print a table of description . before i was doing ajax call and showing the data but the process is slow. So i have to send all the data to the client side and then use javascript to change the table of description on option change. Below is my code
<?php
$data = json_encod开发者_StackOverflow中文版e( get_data_from_db() );
?>
<input type='hidden' name='data' id='data' value= " <?php echo $data; ?>" />
when i do alert in jquery
alert( $("#data").val() );
i only see
{[
value in the alert but when i print the data on the browser it does print in json format ok.
how can i get this data in the javascript and then i have to use loops to extract the data against a specific id and make ul li out of that and then embedd it. please suggest the right approach and whats wrong with the alert. thanks
Another solution - instead of creating global variable, set that data as an data-
attribute of some related element. Don't forget to perform json_encode()
on whole array/object and then htmlspecialchars()
on resulting string (as others have noted, lack of htmlspecialchars()
is the reason why you got only "{[" when alerting value of input field). Don't forget to specify ENT_QUOTES
, when calling htmlspecialchars()
, or you might have invalid results if any value contains apostrophe character.
<?php
$users = array(
array('name' => 'Average', 'surname' => 'Joe'),
array('name' => 'Average', 'surname' => 'Jane'),
array('name' => 'Joe', 'surname' => 'Sixpack'),
array('name' => 'John', 'surname' => 'Doe'),
array('name' => 'Hong', 'surname' => 'Gildong'),
array('name' => 'Foo', 'surname' => 'Bar'),
);
?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<title>sandbox</title>
<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>
<script type='text/javascript' src='js/jquery-1.6.1.min.js'></script>
</head>
<body data-users='<?php echo htmlspecialchars(json_encode($users), ENT_QUOTES); ?>'>
<script type='text/javascript'>
$(function() {
var users = $(document.body).data('users');
for ( var n in users ) {
$('<div/>').text(users[n].name + ' ' + users[n].surname).appendTo(document.body);
}
});
</script>
</body>
</html>
This makes 6 <div/>
elements with all names and surnames as their contents.
The problem you're having is that you're using double quotes around the value
attribute, but of course all keys and strings in the JSON output are in double quotes, the first of which terminates the value
attribute in the HTML.
Don't output $data
as the value of a hidden element. Instead, output it to a JavaScript variable:
<script>
var products_data = <?php echo $data; ?>;
</script>
Then you can use products_data
directly in your JavaScript. (As shown there, it's a global variable, which isn't ideal; if you can contain it within a scoping function, that would be better but it depends on how your scripts and such are organised.)
That works because JSON is a subset of JavaScript object literal format, so valid JSON is also valid JavaScript for defining an object inline. Your PHP will generate something like this and send it to the browser:
<script>
var products_data = {
"products": [
{"id": 427, "name": "WonderWidget", "price": 27.99},
{"id": 429, "name": "CoolNiftyThing", "price": 19.99}
]
};
</script>
Obviously the exact structure will depend on your server-side $data
object.
the reason is that the json encoded array is formatted this way: {[ "value1","value2",...]}
, so, when you echo
the string inside the "value" field the first double quotes in the json
string close the value property of the hidden input
to solve the problem you can do something like
<script>
var myData = <?php echo json_encode( get_data_from_db() ); ?>
</script>
@T.J. Crowder has your answer right on the money.
The reason your are seeing weird behavior in your posted example is probably because your json_encode
has double quotes early on, and it is blowing up the dom when injected into the tag property without escape characters
The best way to do so would not be echoing the JSON structure directly into the script (this can open you up to XSS issues that htmlspecialchars
may not protect you against).
I would recommend doing the following:
<script type="text/plain" id="json_data">
<?php echo html_special_chars(json_encode($data)); ?>
</script>
<script>
var myData = $.parseJSON($("#json_data").text());
</script>
JSON is not Javascript, and should not be treated as such.
not val(); use text();
alert($("#data").text());
精彩评论