如何在 JavaScript 中使用 PHP 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6640761/
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 use a PHP code in JavaScript
提问by Javad Yousefi
I want to use PHP code in JavaScript, but it doesn't work:
我想在 JavaScript 中使用 PHP 代码,但它不起作用:
<script type="text/javascript">
function edit(pollNo)
{
<?php
$result = mysql_query( 'CALL ret_poll('.pollNo.')' );
$row = mysql_fetch_assoc($result);
echo 'document.poll.pollTitle.value='.$row['title'];
?>
}
</script>
回答by Arno Moonen
You could use jQuery to perform an AJAX request to a PHP page that executes the PHP code and pass along the arguments from the JavaScript function. Check out the jQuery website for more information on this subject: http://api.jquery.com/category/ajax/
您可以使用 jQuery 向 PHP 页面执行 AJAX 请求,该页面执行 PHP 代码并传递来自 JavaScript 函数的参数。查看 jQuery 网站以获取有关此主题的更多信息:http: //api.jquery.com/category/ajax/
The big problem in your code is that JavaScript runs on the Client Side and PHP runs on the Server Side. That's why it's impossible to mix these two like this.
您代码中的大问题是 JavaScript 在客户端运行,而 PHP 在服务器端运行。这就是为什么不可能像这样混合这两者。
I wrote this for you, but I haven't tested it. I'm pretty sure it gives you an idea of how to implement this:
我为你写了这个,但我还没有测试过。我很确定它让您了解如何实现这一点:
getpollinfo.php
获取轮询信息.php
<?php
if ( IsSet( $_GET['poll'] ) ) {
/* Connect to MySQL here */
$result = mysql_query( 'CALL ret_poll(' . intval( $_GET['poll'] ) . ')' );
$row = mysql_fetch_assoc($result);
echo json_encode($row);
}
?>
JavaScript code(assuming you've loaded the jQuery framework)
JavaScript 代码(假设您已经加载了 jQuery 框架)
function edit(pollNo)
{
$.get('getpollinfo.php', { 'poll' : pollNo }, function(data) {
$('#pollTitle').html(data.title);
});
}
回答by Starx
Javed, its not that you can't use php in javascript. However the uses are very limited.
Javed,这并不是说您不能在 javascript 中使用 php。但是用途非常有限。
See an example
查看示例
alert('<?php echo "hi"; ?>');
Once the server renders this, the script will be
一旦服务器呈现这个,脚本将是
`alert('hi');` //SO it will alert `hi` now
Mostly, you can use PHP and javascript mixture to create a script you want to run on the run time
大多数情况下,您可以使用 PHP 和 javascript 混合来创建要在运行时运行的脚本
For example
例如
<script>
<?php
$location = $_SESSION['logged'] ? 'admin.php' : 'index.php';
?>
window.location('<?php echo $location; ?>');
</script>
Or Something like this
或者像这样的东西
<script>
<?PHP if($test==true) { ?>
function test() {
//do something;
}
<?php } else { ?>
function test() {
//do something else but not the previous one
}
<?php } ?>
</script>
However, What you are trying is TRYING TO USE PHP CODES AS JAVASCRIPTWhich is not possible !!!!!!!!
但是,您正在尝试的是尝试将PHP 代码用作 JAVASCRIPT,这是不可能的!!!!!!!!!
Instead, you can use AJAX, as other answers suggest, for a workaround.
相反,您可以使用 AJAX,正如其他答案所建议的那样,作为解决方法。
A little demo of your probable solution is
您可能的解决方案的一个小演示是
FILE: myMYSQLPROCESSING.php
文件:myMYSQLPROCESSING.php
// Your connections and other above
$result = mysql_query( 'CALL ret_poll('.$_POST['pollno'].')' );
$row = mysql_fetch_assoc($result);
echo $row['title'];
JS
JS
function edit(pollNo)
{
$.post("myMYSQLPROCESSING.php",
{ "pollno" : pollNo },
function(data) {
// Now data, will contain whatever you echo in myMYSQLPROCESSING.php
// May be a success message or error message
// and do whatever you want with the response
document.poll.pollTitle.value=data; //in your case something like this
}
);
}
This is a jQuery code, if you are not familiar with it.
如果您不熟悉,这是一个 jQuery 代码。
回答by daanl
Javascript = client side.
Javascript = 客户端。
Php = server side.
Php = 服务器端。
You can't combine them the way you use, you will need to use an ajax to do what you want.
你不能按照你使用的方式组合它们,你需要使用 ajax 来做你想做的事。
The sequence will be:
顺序将是:
- javascript: your edit function
- javascript: ajax request to php script
- php: perform query and return result
- javascript: handle the response
- javascript:您的编辑功能
- javascript:对 php 脚本的 ajax 请求
- php:执行查询并返回结果
- javascript:处理响应
回答by Felix Kling
First you have to understand that PHP runs on the server side and JavaScript on the client. Hence you cannot directly invoke PHP code in a JavaScript function by just putting it there.
首先,您必须了解 PHP 在服务器端运行,而 JavaScript 在客户端运行。因此,您不能通过将其放在 JavaScript 函数中直接调用 PHP 代码。
When the client makes a request, the PHP interpreter executes the code and produces some output. This output is sent to the browser and there the JavaScript code is executed. PHP's job is already done at this point.
当客户端发出请求时,PHP 解释器会执行代码并产生一些输出。该输出被发送到浏览器并在那里执行 JavaScript 代码。此时 PHP 的工作已经完成。
You achieve what you want with Ajax(though I think you have to learn more about JavaScript, PHPand HTTPfirst).
您可以使用Ajax实现您想要的(尽管我认为您必须首先了解有关JavaScript、PHP和HTTP 的更多信息)。
But to give you an example (using the jQuerylibrary):
但是给你一个例子(使用jQuery库):
function edit(pollNo){
$.get('get_poll.php',{id: pollNo}, function(data) {
$('input[name="pollTitle"]').val(data);
});
}
Where your PHP file looks like:
您的 PHP 文件如下所示:
// db connection...
$result = mysql_query( 'CALL ret_poll('.mysql_real_escape_string($_GET['id'].')' );
$row = mysql_fetch_assoc($result);
echo $row['title'];
回答by Shoe
回答by Ribose
If you need to do what your saying, you will end up just rendering the page with that specific Javascript code version.
如果你需要按照你说的去做,你最终只会用那个特定的 Javascript 代码版本来渲染页面。
If you really want to do that you have to look at the output to see that you need to quote strings in Javascript.
如果您真的想这样做,您必须查看输出以了解您需要在 Javascript 中引用字符串。
<script type="text/javascript">
function edit(pollNo)
{
<?php
$result = mysql_query( 'CALL ret_poll('.pollNo.')' );
$row = mysql_fetch_assoc($result);
echo 'document.poll.pollTitle.value="'.$row['title'].'"';
?>
}
</script>
Your browser will end up with:
您的浏览器最终将显示:
<script type="text/javascript">
function edit(pollNo)
{
document.poll.pollTitle.value="somehardcodedtext";
}
</script>
You will have to consider escaping quote symbols in the output of $row['title']
and whether you would rather just call the server using AJAX instead.
您将不得不考虑在输出中转义引号,$row['title']
以及是否更愿意使用 AJAX 调用服务器。