简体   繁体   English

如何将 PHP 和 Javascript 组合在一起?

[英]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.我的 Javascript 脚本中有一个 function 需要与 PHP 对话以获取数据库中的数据。 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.但是我遇到了一个小问题,因为我在 Javascript 的 for 循环中启动了 PHP,然后在该 for 循环中我得到了数据库中的数据。 But the pointer in the for loop inside the PHP code is not working.. I guess the problem is in escaping?但是 PHP 代码内的 for 循环中的指针不起作用.. 我猜问题出在 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.我想你很困惑,你试图在 php 中使用 javascript 的变量。

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.如果i是在客户端生成的变量,您怎么可能知道i的值?不要混淆想法, i是在浏览器中定义的,php 代码在服务器上。

1.Pass the javascript variable to the URL to another php page. 1.将 javascript 变量传递给 URL 到另一个 php 页面。

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

2.Then you can use this variable using $_GET in the php script. 2.然后您可以在 php 脚本中使用 $_GET 来使用此变量。

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

3.Perform any server side operation in the Php and pass this result. 3. 在 Php 中执行任何服务器端操作并传递此结果。

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

4.Redirect back to the page you started from thus passing the result of PHP. 4.重定向回您开始的页面,从而传递 PHP 的结果。

Php and Javascript have different roles in web development. Php 和 Javascript 在 web 开发中的作用不同。 This task can also be performed if there's a php script and js in the same page.如果在同一页面中有php脚本和js,也可以执行此任务。 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.您可能需要考虑使用 PHP 到 output 文件 JavaScript 文件,这样 Z2FEC392324A5C29B7CZDA 变量将在任何地方可用。

The following links better explain this.以下链接更好地解释了这一点。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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