Javascript 如何在javascript中执行php代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12498839/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:32:36  来源:igfitidea点击:

how to execute php code within javascript

phpjavascript

提问by Tony

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
    function funk(){
        alert("asdasd");
        <?php echo "asdasda";?>
    }
</script>

When the button is pressed i want to execute php code (at this point to echo asadasda)

当按钮被按下时,我想执行 php 代码(此时回应 asadasda)

回答by JKirchartz

You could use http://phpjs.org/http://locutus.io/php/it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:

你可以使用http://phpjs.org/http://locutus.io/php/它将一堆 PHP 功能移植到 javascript,但如果它只是回声,并且脚本在一个 php 文件中,你可以做一些事情像这样:

alert("<?php echo "asdasda";?>");

don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.

不要担心双引号的使用看起来很狡猾,PHP 会在浏览器看到它之前呈现它。

as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:

至于使用ajax,最简单的方法是使用一个库,比如jQuery。有了它,你可以:

$.ajax({
  url: 'test.php',
  success: function(data) {
    $('.result').html(data);
  }
});

and test.php would be:

和 test.php 将是:

<?php 
  echo 'asdasda';
?>

it would write the contents of test.php to whatever element has the resultclass.

它会将 test.php 的内容写入具有result该类的任何元素。

回答by jobeard

Interaction of Javascript and PHP

Javascript 和 PHP 的交互

We all grew up knowing that Javascript ran on the Client Side (ie the browser) and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.

我们从小就知道 Javascript 运行在客户端(即浏览器),而 PHP 是一个服务器端工具(即服务器端)。很明显,两人无法互动。

But -- good news; it can be made to work and here's how.

但是——好消息;它可以工作,这里是如何工作。

The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.

目标是从服务器获取一些动态信息(比如服务器配置项)到 Javascript 环境中,以便在需要时使用 - 通常这意味着对演示文稿进行 DHTML 修改。

First, to clarify the DHTML usage I'll cite this DHTML example:

首先,为了阐明 DHTML 的用法,我将引用这个 DHTML 示例:

<script type="text/javascript">

function updateContent() {
 var frameObj = document.getElementById("frameContent");
 var y = (frameObj.contentWindow || frameObj.contentDocument);

 if (y.document) y = y.document;
 y.body.style.backgroundColor="red";  // demonstration of failure to alter the display

 // create a default, simplistic alteration usinga fixed string.
 var textMsg = 'Say good night Gracy';

 y.write(textMsg);

 y.body.style.backgroundColor="#00ee00";  // visual confirmation that the updateContent() was effective

}
</script>

Assuming we have an html file with the ID="frameContent" somewhere, then we can alter the display with a simple < body onload="updateContent()" >

假设我们在某处有一个 ID="frameContent" 的 html 文件,那么我们可以使用简单的 <body onload="updateContent()" > 更改显示

Golly gee; we don't need PHP to do that now do we! But that creates a structure for applying PHP provided content.

天啊!我们现在不需要 PHP 来做到这一点,对吧!但这为应用 PHP 提供的内容创建了一个结构。

We change the webpage in question into a PHTML type to allow the server side PHP access to the content:

我们将有问题的网页更改为 PHTML 类型,以允许服务器端 PHP 访问内容:

**foo.html becomes foo.phtml**

and we add to the top of that page. We also cause the php data to be loaded into globals for later access - - like this:

我们添加到该页面的顶部。我们还会将 php 数据加载到全局变量中以供以后访问 - - 像这样:

<?php
   global $msg1, $msg2, $textMsgPHP;

function getContent($filename) {
    if ($theData = file_get_contents($filename, FALSE)) {
        return "$theData";
    } else {
        echo "FAILED!";
        }
}
function returnContent($filename) {

  if ( $theData = getContent($filename) ) {
    // this works ONLY if $theData is one linear line (ie remove all \n)
    $textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
    return "$textPHP";
  } else {
    echo '<span class="ERR">Error opening source file :(\n</span>';  # $filename!\n";
  } 
}

// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 =       returnContent('dummy_frame_data.txt');
$msg2 =       returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');

?>

Now our javascripts can get to the PHP globals like this:

现在我们的 javascripts 可以像这样访问 PHP 全局变量:

// by accessig the globals var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';

// 通过访问全局变量 var textMsg = '< ? php 全局 $textMsgPHP; echo "$textMsgPHP"; ? >';

In the javascript, replace

在javascript中,替换

var textMsg = 'Say good night Gracy';

var textMsg = '说晚安格雷西';

with: // using php returnContent()

with: // 使用 php returnContent()

var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';

var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); 回声“$msgX”?>';

Summary:

概括:

  • the webpage to be modified MUST be a phtml or some php file
  • the first thing in that file MUST be the < ? php to get the dynamic data ?>
  • the php data MUST contain its own css styling (if content is in a frame)
  • the javascript to use the dynamic data must be in this same file
  • and we drop in/outof PHP as necessary to access the dynamic data
  • Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
  • 要修改的网页必须是 phtml 或一些 php 文件
  • 该文件中的第一件事必须是 < ? php 获取动态数据?>
  • php 数据必须包含它自己的 css 样式(如果内容在框架中)
  • 使用动态数据的 javascript 必须在同一个文件中
  • 我们根据需要插入/退出 PHP 以访问动态数据
  • 注意:- 在外部 javascript 中使用单引号,在动态 php 数据中仅使用双引号

To be resolved: calling updateContent()with a filename and using it via onClick()instead of onLoad()

待解决:使用文件名调用updateContent()并通过onClick()而不是onLoad()使用它

An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it

Sample_Dynamic_Frame.zip 中可以提供一个示例供您检查,但没有找到附加方法

回答by Pez Cuckow

You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).

你不能用 javascript 运行 PHP。JavaScript 是客户端技术(在用户浏览器中运行),PHP 是服务器端技术(在服务器上运行)。

If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.

如果你想这样做,你必须向 PHP 脚本发出一个 ajax 请求,并让它返回你正在寻找的结果。

Why do you want to do this?

你为什么要这样做?

回答by Josh Harrison

If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:

如果您只想在用户单击按钮时在页面上的某个位置回显来自 PHP 的消息,您可以执行以下操作:

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
  alert("asdasd");
  document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>

However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/- use jQuery to load the path to the php script which does the processing. In your example you could do:

但是,假设您的脚本需要进行一些服务器端处理,例如将商品添加到购物车,您可能想查看 jQuery 的http://api.jquery.com/load/- 使用 jQuery 加载到执行处理的php脚本。在您的示例中,您可以执行以下操作:

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
  alert("asdasd");
  $('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>

This runs the php script and loads whatever message it returns into <div id="resultMsg">.

这将运行 php 脚本并加载它返回的任何消息<div id="resultMsg">

order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:

order_item.php 会将项目添加到购物车,并只回显您想要显示的任何消息。要使示例正常工作,这将满足 order_item.php:

<?php
// do adding to cart stuff here
echo 'Added to cart';
?>

For this to work you will need to include jQuery on your page, by adding this in your <head>tag:

为此,您需要在您的页面上包含 jQuery,方法是在您的<head>标签中添加以下内容:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

回答by Shafiul Hasan

Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below

任何服务器端的东西,比如 php 声明,都必须在脚本标签内的主机文件(带有 .php 扩展名的文件)中进行评估,如下所示

<script type="text/javascript">
    var1 = "<?php echo 'Hello';?>";
</script>

Then in the .js file, you can use the variable

然后在 .js 文件中,你可以使用变量

alert(var1);

If you try to evaluate php declaration in the .js file, it will NOT work

如果您尝试评估 .js 文件中的 php 声明,它将不起作用

回答by bodomalo

If you do not want to include the jquery library you can simple do the following

如果您不想包含 jquery 库,您可以简单地执行以下操作

a) ad an iframe, size 0px so it is not visible, href is blank

a) 广告 iframe,大小为 0px 所以它不可见,href 为空

b) execute this within your js code function

b) 在你的 js 代码函数中执行这个

 window.frames['iframename'].location.replace('http://....your.php');

This will execute the php script and you can for example make a database update...

这将执行 php 脚本,您可以例如进行数据库更新...

回答by jugn

put your php into a hidden div and than call it with javascript

将你的 php 放入一个隐藏的 div 中,然后用 javascript 调用它

php part

php部分

<div id="mybox" style="visibility:hidden;"> some php here </div>

javascript part

javascript部分

var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';

now, you can do anything with myfield...

现在,你可以用 myfield 做任何事情......

回答by Nick

May be this way:

可能是这样:

    <?php 
     if($_SERVER['REQUEST_METHOD']=="POST") {
       echo 'asdasda';
     }
    ?>

    <form method="post">
    <button type="submit" id="okButton">Order now</button>
</form>