开发者

How can I echo text to a backend script with Javascript?

I have a PHP script which I want to output some text which I'm calling with AJAX to place in a textbox. The text is generated with JavaScript but if I call document.write() then the whole page is refreshed and the text is displayed on its own - not in the textbox.

Here is the backend script:

<?php
  // unrelated stuff
?>
<!DOCTYPE HTML>

<html>
  <head>

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <meta name="robots" content="NOINDEX, NOFOLLOW" />
    <!-- JQuery -->
    <script type="text/javascript" src="<?php echo $toolsDirectory; ?>/jquery-1.4.3.min.js"></script>

<?php if ($a = 2) { ?>
    <script src="someScript.js" type="text/javascript"></script>

    <script type="text/javascript">
      <!--
      var a = new A;
      document.write(a.go("<?php echo $testString; ?>"1));
      // -->
    </script>

<?php } ?>
  </head>
  <body>

  </body>
</html>

I'm calling it with $("#output").load("script.php");.

I have also tried $(body).html() with the same result.

So just to sum up - the Javascript works, it outputs the right stuff. If I just echo "hello" in the PHP, it loads it into the textbox as expec开发者_运维百科ted - it's just the Javascript writing that is confusing me.


A document can be in two states — open and closed.

While loading a document, it is open. Once it has finished loading, it is closed.

If you reopen a document, it wipes out everything in it.

If you try to write to a document, and it is in a closed state, then it automatically opens it.

This is what is happening to you.

Forget about document.write and use DOM methods to modify the document instead.


Not sure I understand why you're using javascript to echo content, when you're able to just use php...

<?php if ($a = 2) { ?>
    <script src="someScript.js" type="text/javascript"></script>
<?php echo $testString; } ?>

edit: as you're passing it to a JS function, you'll have to use normal methods for changing content in the page... i.e. give this a shot:

<?php if ($a = 2) { ?>
<div id="aresult"></div>
 <script src="someScript.js" type="text/javascript"></script>
 <script>
 var a = new A;
 $('#aresult').html(a.go('<?php echo $testString; ?>'));
 </script>
<?php } ?>

This way you're executing the javascript function normally, and putting the result somewhere on the page. It can't just be echo'd in place as in the original code.


Check out my answer to this question:

JavaScript: How do I create JSONP?

The idea is - you make a call from JavaScript (client side) to a separate PHP script (server side). It generates some text and returns the name of the callback JS function with parameter (which can be your generated text). Callback JS function executes on client side and processes that parameter data.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜