Currently I using the following code to get my JSON output from MySQL.
<?php
$session = mysql_connect('localhost','name','pass');
mysql_select_db('dbname', $session);
$result= mysql_query('SELECT message FROM posts', $session);
$somethings = array();
while ($row = mysql_fetch_assoc($result)) {
$somethings[] = $row;
}
?>
<script type="text/javascript">
var somethings= <?php echo json_encode($somethings); ?>;
</script>
And the output is:
<script type="text/javascript">
var somethings= [{"message":"Welcome to Yo~ :)"},{"message":"Try iPhone post!"},{"message":"????" (the ???? meant to be chinese character)}];
</script>
Here is the question, how can I change my output into format like :
<script type="text/javascript">
userAge = new Array('21','36','20'),
userMid = new Array('liuple','anhu','jacksen');
</script>
Which I’ll be using later with following code :
var html = '
<table class="map-overlay">
<tr>
<td class="user">' +
'<a class="username" href="/' + **userMid[index]** + '" target="_blank"><img alt="" src="' +
getAvatar(signImgList[index], '72x72') +
'"></a><br>
<a class="username" href="/' + **userMid[index]** + '" target="_blank">' +
userNameList[index] +
'</a><br>
<span class="info">' + **userSex[index]** + ' ' + **userAge[index]** + '岁<br>
' +
cityList[index] +
'</span>' +
'</td>
<td class="content">' + picString
+ somethings[index] + '<br>
<span class="time">' +
timeList[index] + picTips +
'</span></td>
</tr>
</table>
';
Also how can my json output support chinese character?
Thanks for helping and reading!
Best guessing your question:
How to change this JSON format:
To this format:
The answer is: You shouldn’t. JSON is a good data format to work with, and it’s self-contained. If you change what would normally be keys of a JSON object to variables, you’re making your “data format” extremely dependent on where it’s going to be used. Variable name conflicts are almost guaranteed. There’s also no advantage, data in JSON objects is trivial to access already.
Update:
You could easily build this format by looping through your results, putting them into arrays and printing out Javascript code, it’s not difficult. Despite that I’m not going to post the code here, since it’s terrible practice. Instead, all you need to do is slightly change the code that will use this data:
As for Chinese characters, Javascript/JSON is intrinsically UTF8, so it has no problems with Chinese characters. Just make sure your characters are UTF8 encoded when you package them as JSON.