开发者

Extracting information from PHP to JavaScript

I've been stuck for hours now trying to pass a few pieces of information from a PHP script to JavaScript. The PHP script echoes out HTML and I've figured there might be a problem with this if I'm to try and send the JavaScript a JSON object through 开发者_C百科AJAX. The thing is, all the arrays and such are made within the PHP file which echoes out the results, so what I have done is to try and json_encode those arrays/and or echo them out somehow.

Is it even possible for me to send the information this way? The only thing I can think of would be to write those arrays into a new file and then explode it up into new ones and similar. Not a very fun thought.

To give you an idea of what my PHP looks like:

echo "<html here>";
echo "<html here>";
echo "<html here>";
echo json_encode($array);


Just build your HTML/JavaScript code from PHP...

Simple example (PHP)

<?php

  $phpvariable = 'test variable from php';

  echo "<html>\n<head>\n</head>\n<body>\n";
  echo "<script type=\"text/javascript\">\n";
  echo "  myPHPvar = '$phpvariable';\n";
  echo "  alert(myPHPvar);\n";
  echo "</script>\n";
  echo "</body>\n</html>";

?>

Output (HTML)

<html>
<head>
</head>
<body>
<script type="text/javascript">
  myPHPvar = 'test variable set in php';
  alert(myPHPvar);
</script>
</body>
</html>

Output (Browser)

Extracting information from PHP to JavaScript

JavaScript variable myPHPvar gets value from PHP variable $phpvariable. That is the simplest way to pass variable from PHP to JavaScript.


What's your question? What are you trying to achieve in javascript with your data from PHP? Does the ajax call work at all? In general I'd recommend separating HTML construction from providing array data as json. You'd like to handle both in one single PHP call, don't you? You could attach html parts to you array and send json only, or have array data in a fake html element, that you might exclude from display later. Depends on how complex both parts are. Give some more example code and information, please.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜