loop through php within Javascript
I am running a javascript file either on my hard drive or from my website, right now, I have been trying to get this to work from my hard drive. The javascript loops through and builds a table with x number of rows. Each row has a "textarea" box where users can type in mutual funds ticker symbols. I would like to populate the textarea boxes with data from a mysql database. From the advice I got f开发者_运维问答rom Will, I am using a PHP file to return JSON, but I can't figure out how to iterate through the JSON and put one fund symbol in each row of my javascript table.
below is my php file on my website
<?php
$connect = >>>>>my connection string here<<<<<;
mysql_select_db("altatech_grid");
$result = mysql_query("SELECT FSymbol FROM FundSymbols");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
$to_encode[] = $row['FSymbol'];
}
$myFund = json_encode($to_encode);
echo ($myFund);
?>
which returns this below <<<<<<
["FDGRX","FVINX","VCVLX","LLPFX "]
this is my javascript below <<<<<<<
document.write("<table>");
nButtons = 0;
for (row = 1; row < nItems; row++)
{
document.write("<tr>");
for (rowButton = 0; rowButton < row; rowButton++)
document.write("<td><textarea class='unorderedlist' wrap='soft' name='possibility" + (row+1) + "' id='p" + (row+1) + "'>")";
########### This Is Where The PHP Needs To Put One Item In Each Row ############
document.write("</textarea></td>");
document.write("</tr>");
document.write("</table>");
}
This isn't JSON, it's an array...
var i;
var html = "<textarea>";
var symbols = ["FDGRX","FVINX","VCVLX","LLPFX"];
for (i = 0; i < symbols.length; i++) {
html += symbols[i] + "\r\n";
}
var html += "</textarea>";
document.write(html);
JSON objects look like this:
var jsonObject = { name: "John", location: "UK" };
And you could add your dynamic values like this:
var symbols = <?php echo $myFund; ?>;
I think that there is no way to do like you want. Because, PHP is script run at server. So you could not run a PHP script from client using Javascript. But you can do like below:
<script type="text/javascript">
var data = <?php echo json_encode($to_encode);?>;
//At client it will be:
//var data = ["FDGRX","FVINX","VCVLX","LLPFX"];
//Then you can loop:
for(var row = 0; row < data.length; row++)
{
//@Todo
//.................
document.write(data[row]);
}
</script>
精彩评论