如何将 PHP 和 Javascript 结合在一起?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6334146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to combine PHP and Javascript together?
提问by Kevin Lee
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.
我的 Javascript 脚本中有一个函数需要与 PHP 对话以获取数据库中的数据。但是我遇到了一个小问题,因为我在 Javascript 的 for 循环中启动 PHP,然后在 for 循环中我在我的数据库中获取数据。但是 PHP 代码中 for 循环中的指针不起作用.. 我猜问题出在转义上?或者,这根本不可能。
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: ....
};
};
});
回答by cyraxjoe
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代码在服务器上。
回答by Drazisil
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 来输出 JavaScript 文件,这样 PHP 变量将在您想要的任何地方可用。
The following links better explain this.
以下链接更好地解释了这一点。
http://www.givegoodweb.com/post/71/javascript-php
http://www.givegoodweb.com/post/71/javascript-php
回答by Amar
1.Pass the javascript variable to the URL to another php page.
1.将javascript变量传递给另一个php页面的URL。
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. 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.
PHP 和 Javascript 在 Web 开发中扮演着不同的角色。如果同一页面中存在 php 脚本和 js,也可以执行此任务。但我留给读者来解决。
Hope this helps!!
希望这可以帮助!!