简体   繁体   中英

How to combine PHP and Javascript together?

I have a function in my Javascript script that needs to talk with the PHP to get the data in my database. But I'm having a small problem because I start the PHP in the for loop in Javascript, and then inside that for loop I get the data in my database. But the pointer in the for loop inside the PHP code is not working.. I guess the problem is in escaping? Or maybe it's not possible at all.

Here's my code:

(function() {
  var data = [];
  for(var i = 0; i < 25; i++) {
    data[i] = {
       data1: "<a href='<?= $latest[?>i<?=]->file; ?>'><?= $latest[?>i<?=]->title; ?></a>", // The problems
       data2: ....
    };
  };
});

I think you are confused, you are trying to use a variable of javascript in php.

You cannot do this:

<?= $latest[?>i<?=]->file; ?>'

Which expands to:

<?php
   $latest[
?>
 i
<?php
]->file;
?>

how can you possibly know the value of i , if i is a variable generated in the client side?, do not mix the ideas, i is defined in the browser and the php code is on the server.

1.Pass the javascript variable to the URL to another php page.

window.open("<yourPhpScript>.php?jsvariable="+yourJSVariable);

2.Then you can use this variable using $_GET in the php script.

$jsVaribleInPhp=$GET['jsvariable'];
//do some operation
$yourPhpResult;

3.Perform any server side operation in the Php and pass this result.

header("Location:<your starting page>?result=".$yourPhpResult);

4.Redirect back to the page you started from thus passing the result of PHP.

Php and Javascript have different roles in web development. This task can also be performed if there's a php script and js in the same page. But that I leave for the readers to work it out.

Hope this helps!!

You may want to consider using PHP to output the JavaScript file, that way the PHP variables will be available wherever you want them.

The following links better explain this.

http://www.givegoodweb.com/post/71/javascript-php

http://www.dynamicdrive.com/forums/showthread.php?t=21617

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