简体   繁体   中英

PHP pass array item to javascript

I'm having some difficulties in passing an array item from PHP to a Javascript function.

I have a txt file which is something like this:

recipe1 flour milk
recipe2 egg milk
recipe3 flour salt

I read txt file and need to list all recipes in a list:

recipe1
recipe2
recipe3

When a user clicks on any recipe the corresponding ingredients will be shown in a textarea.

In my example I will display in textarea

flour milk 

if users click on recipe1,

egg milk

if users click on recipe2, etc.

So here's my code:

This is the JavaScript which will populate the textarea with the text I will pass to it.

<script language="javascript" type="text/javascript">
function addtext(text){
document.testForm.cmd.value +=text;
}
</script>

Here's the code which reads line by line the txt file and put

recipe1, recipe2, recipe3, etc. in an array flour milk, egg milk, flour salt, etc. in another array.

<?php

$recipe=array();
$ingredient=array();

$fp=fopen("recipes.txt", "r");
while (!feof($fp))
{
    $line=fgets($fp);

    $line=explode(' ', $line, 2);

    $recipe[]=$line[0];
    $ingredient[]=$line[1];

}
fclose($fp);

//Print elements
$i=0;
foreach ($recipe as $rec) {

echo '<a href="#" onclick="addtext(\''.$ingredient[$i].'\'); return false">' . $rec . '</a><br />';

$i++;

}


?>

Recipe list works correclty, I cannot pass $ingredient[$i] to Javascript addtext function. I've tried without success using:

$value = echo json_encode($ingredient[$i])

Any help is appreaciated,

Thanks in advance.

I prefer to json_encode() the entire array and pass it along to JavaScript. Here's a very rudimentary example:

<?php

$fruits = array(
  'cherry',
  'grape',
  'orange',
);

print '<script>var fruits = ' . json_encode($fruits) . ';</script>';

Then in Javascript:

console.log(fruits);

will show you what you have to work with, namely:

["cherry", "grape", "orange"] 

thus fruits[1] returns grape .

Generally you should render the <script> contents, for example, like this (just the idea, not the exact code):

echo '<script language="">
      var value = ' . json_encode($ingredient[$i]) . 
      '</script>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM