如何使用PHP打印JavaScript [英] How to print JavaScript with PHP

查看:76
本文介绍了如何使用PHP打印JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些JS变量传递给PHP,并且遇到了一些麻烦.

I need to pass some JS variable to PHP and am having some trouble.

我尝试了以下操作:

$product_id = "<script> var prod_id_one = $('ul.products li:nth-child(1) a.button').attr('data-product_id')</script>";
echo $product_id;

但这只是将其打印为字符串:

But this just prints it as a string:

`<script> var prod_id_one = $('ul.products li:nth-child(1) a.button').attr('data-product_id');</script>`

我将如何存储该JS变量,然后使用PHP echo将其存储?我对PHP还是很陌生,因此不胜感激!

How would I store that JS variable and then echo it using PHP? I am quite new to PHP, so any help would be appreciated!

推荐答案

按照自己的方式进行操作,这是不可能的. PHP无法直接在同一页面中读取"或与JavaScript进行交互".

By doing it your way, it's just impossible. PHP can't "read" or "interact with" javascript directly in the same page.

您必须了解PHP是预处理器,它在服务器上生成HTML,然后将生成的页面发送到客户端.在此页面中,PHP代码已完全消失.您只能看到它生成的内容(即HTML或JS).然后,运行javascript代码,并且不知道它是使用PHP生成的,也不知道PHP的存在.

You have to understand that PHP is a preprocessor, it generates HTML on the server, then the generated page is sent to the client. In this page, the PHP code has entirely disappeared. You can only see what it generated (that is, HTML or JS). Then, the javascript code runs, and it has no idea it was generated using PHP, and no idea of PHP's presence whatsoever.

为了将变量传递给PHP脚本,您必须使用GET或POST方法调用文件:

In order to pass variables to a PHP script, you have to call the file with GET or POST methods :

(JS)

$.get( 'myScript.php', { // This is calling the PHP file, passing variables (use get or post)
     variable1 : "Hello",
     variable2 : "world!"
   }, function(data){ // PHP will then send back the response as "data"
      alert(data); // will alert "Hello world!"
});

(myScript.php)

(myScript.php)

    $variable1 = $_GET['variable1']; // or POST if you're using post
    $variable2 = $_GET['variable2'];

    echo $variable1 . " " . $variable2; // Concatenates as "Hello world!" and prints it out.
//The result of the PHP file is sent back to Javascript when it's done.

当然,这是一个非常基本的示例.切勿直接读取和使用发送到PHP的内容(就像我刚才所做的那样),因为任何人都可以注入他们想要的内容. 添加证券.

Of course, this is a very basic example. Never read and use directly what is sent to PHP (as I just did), because anyone could inject whatever they'd want. Add securities.

这篇关于如何使用PHP打印JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆