Mad*_*iha 642 javascript php
我在PHP中有一个变量,我需要在我的JavaScript代码中使用它的值.如何将我的变量从PHP变为JavaScript?
我的代码看起来像这样:
<?php
     ...
     $val = $myService->getValue(); // Makes an API and database call
?>
我有需要的JavaScript代码,val并且看起来如下:
<script>
    myPlugin.start($val); // I tried this, but it didn't work
    <?php myPlugin.start($val); ?> // This didn't work either
    myPlugin.start(<?=$val?> // This works sometimes, but sometimes it fails
</script>
Mad*_*iha 851
实际上有几种方法可以做到这一点.有些需要比其他更多的开销,有些被认为比其他更好.
没有特别的顺序:
在这篇文章中,我们将研究上述每种方法,并查看每种方法的优缺点,以及如何实现它们.
此方法被认为是最好的,因为您的服务器端和客户端脚本是完全独立的.
使用AJAX,您需要两个页面,一个是PHP生成输出的位置,第二个是JavaScript获取输出的位置:
/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 *
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well.
 * It all depends on the Content-type header that you send with your AJAX
 * request. */
echo json_encode(42); // In the end, you need to echo the result.
                      // All data should be json_encode()d.
                      // You can json_encode() any value in PHP, arrays, strings,
                      //even objects.
<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }
    var oReq = new XMLHttpRequest(); // New request object
    oReq.onload = function() {
        // This is where you handle what to do with the response.
        // The actual data is found on this.responseText
        alert(this.responseText); // Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->
42当文件完成加载时,上述两个文件的组合将发出警报.
这种方法不如AJAX优选,但它仍然有其优点.从某种意义上说,PHP和JavaScript之间仍然存在相对分离,即JavaScript中没有PHP.
<input type=hidden>来存储信息,因为它更容易从中获取信息inputNode.value,但这样做意味着您在HTML中有一个无意义的元素.HTML具有<meta>关于文档的数据的元素,HTML 5引入data-*了专门用于与JS一起阅读的数据的属性,可以与特定元素相关联.有了这个,我们的想法是创建一些不会向用户显示但是对JavaScript可见的元素.
<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php
        $output = "42"; // Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->
这可能是最容易理解的,也是最恐怖的.除非你知道自己在做什么,否则不要这样做.
实施相对简单:
<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->
祝好运!
Ben*_*aum 87
我打算尝试一个更简单的答案:
首先,让我们了解从我们的服务器提供页面时的事件流程:
所以,真正需要记住的核心是HTTP是无状态的.请求离开服务器后,服务器无法触及它.所以,这留下了我们的选择:
这是你应该问自己的核心问题是:
网站主要是基于页面的,页面加载时间需要尽可能快(例如 - 维基百科).Web应用程序更加庞大,并且执行大量往返以获取客户端的快速信息(例如 - 股票仪表板).
在初始请求完成后从客户端发送更多请求的速度很慢,因为它需要更多具有大量开销的HTTP请求.此外,它需要异步,因为AJAX请求需要处理程序才能完成.
除非您的站点是从服务器获取该信息的应用程序,否则我不建议再发出请求.
您需要快速响应时间,这会对转换和加载时间产生巨大影响.在这种情况下,对于初始正常运行时间而言,ajax请求的速度很慢且不需要.
您有两种方法可以解决这个问题
设置一个cookie真的不是很难,你只需为它赋值:
setcookie("MyCookie", $value); // Sets the cookie to the value, remember, do not
                               // Set it with HTTP only to true.
然后,您可以使用JavaScript阅读使用document.cookie:
这是一个简短的手动解析器,但我在上面链接的答案有更好的测试:
var cookies = document.cookie.split(";").
    map(function(el){ return el.split("="); }).
    reduce(function(prev,cur){ prev[cur[0]] = cur[1];return prev },{});
cookies["MyCookie"] // Value set with PHP.
Cookie适用于少量数据.这就是跟踪服务经常做的事情.
一旦我们有了更多数据,我们就可以在JS变量中使用JSON对其进行编码:
<script>
    var myServerData = <?=json_encode($value)?>; // Don't forget to sanitize
                                                 //server data
</script>
假设$value是json_encode能够在PHP端(通常是这样).这种技术就是StackOverflow的聊天功能(例如只使用.net而不是php).
如果您正在编写应用程序 - 突然之间,初始加载时间并不总是与应用程序的持续性能一样重要,并且它开始为单独加载数据和代码而付出代价.
我在这里的答案解释了如何在JavaScript中使用AJAX加载数据:
function callback(data){
    // What do I do with the response?
}
var httpRequest = new XMLHttpRequest;
httpRequest.onreadystatechange = function(){
    if (httpRequest.readyState === 4) { // Request is done
        if (httpRequest.status === 200) { // successfully
            callback(httpRequest.responseText); // We're calling our method
        }
    }
};
httpRequest.open('GET', "/echo/json");
httpRequest.send();
或者使用jQuery:
$.get("/your/url").done(function(data){
    // What do I do with the data?
});
现在,服务器只需要包含一个/your/url路由/文件,其中包含抓取数据并对其执行某些操作的代码,在您的情况下:
<$php
     ...
     $val = myService->getValue(); // Makes an API and database call
     echo json_encode($val); // Write it to the output
 $>
这样,我们的JS文件会询问数据并显示它,而不是要求代码或布局.当应用程序变得更高时,这更清洁并开始获得回报.它也更好地分离了关注点,它允许测试客户端代码,而不涉及任何服务器端技术,这是另一个优点.
后记:当你从PHP注入任何东西时,你必须非常了解XSS攻击向量.正确地逃避价值并且它对上下文敏感是非常困难的.如果你不确定如何处理XSS,或者不知道它 - 请阅读这篇OWASP文章,这篇文章和这个问题.
yui*_*nnu 82
我通常在html中使用data-*属性.
<div class="service-container" data-service="<?php echo $myService->getValue(); ?>">
</div>
<script>
    $(document).ready(function() {
        $('.service-container').each(function() {
            var container = $(this);
            var service = container.data('service');
            // Service variable now contains the value of $myService->getValue();
        });
    });
</script>
这个例子使用jQuery但可以适用于另一个库或vanilla Javascript.
您可以在此处阅读有关数据集属性的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset
Jes*_*nck 37
<script>
  var jsvar = <?php echo json_encode($PHPVar); ?>;
</script>
json_encode()需要:
$PHPVar 编码为UTF-8,Unicode.Nis*_*tta 17
只需使用以下方法之一即可.
<script type="text/javascript">
var js_variable  = '<?php echo $php_variable;?>';
<script>
要么
<script type="text/javascript">
    var js_variable = <?php echo json_encode($php_variable); ?>; 
</script>
Dan*_*jel 10
我非常喜欢Wordpress使用enqueue和localize函数的方式,所以在这个模型之后,我编写了一个简单的类,用于根据脚本依赖关系将脚本放入页面,以及为脚本提供额外的数据.
class mHeader {
    private $scripts = array();
    /**
     * @param string $id        Unique script identifier
     * @param string $src      Script src attribute
     * @param array  $deps       An array of dependencies ( script identifiers ).
     * @param array  $data       An array, data that will be json_encoded and available to the script.
     */
    function enqueue_script($id, $src, $deps = array(), $data = array()) {
        $this->scripts[$id] = array('src' => $src, 'deps' => $deps, 'data' => $data);
    }
    private function dependencies($script) {
        if ($script['deps']) {
            return array_map(array($this, 'dependencies'), array_intersect_key($this->scripts, array_flip($script['deps'])));
        }
    }
    private function _unset($key, &$deps, &$out) {
        $out[$key] = $this->scripts[$key];
        unset($deps[$key]);
    }
    private function flattern(&$deps, &$out = array()) {
        foreach($deps as $key => $value) {
            empty($value) ? $this->_unset($key, $deps, $out) : $this->flattern( $deps[$key], $out);
        }
    }
    function print_scripts() {
        if (!$this->scripts)
            return;
        $deps = array_map(array($this, 'dependencies'), $this->scripts);
        while ($deps)
            $this->flattern($deps, $js);
        foreach($js as $key => $script) {
            $script['data'] && printf("<script> var %s = %s; </script>" . PHP_EOL, key($script['data']), json_encode(current( $script['data'])));
            echo "<script id=\"$key-js\" src=\"$script[src]\" type=\"text/javascript\"></script>" . PHP_EOL;
        }
    }
}
调用enqueue_script()函数用于添加脚本,设置其他脚本的源和依赖项以及脚本所需的其他数据.
$header = new mHeader();
$header->enqueue_script('jquery-ui', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js', array('jquery'));
$header->enqueue_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');
$header->enqueue_script('custom-script', '//custom-script.min.js', array('jquery-ui'), array('mydata' => array('value' => 20)));
$header->print_scripts();
并且,print_scripts()上面示例的方法将发送此输出:
<script id="jquery-js" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script id="jquery-ui-js" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js" type="text/javascript"></script>
<script> var mydata = {"value":20}; </script>
<script id="custom-script-js" src="//custom-script.min.js" type="text/javascript"></script>
无论脚本'jquery'在'jquery-ui'之后排队,它都会被打印,因为它在'jquery-ui'中定义它依赖于'jquery'."自定义脚本"的附加数据位于新的脚本块中,并放置在它的前面,它包含mydata保存其他数据的对象,现在可用于"自定义脚本".
试试这个
<?php
    echo "<script> var x = " . json_encode($phpVariable) . "</script>";
?>
-
- 尝试了一段时间虽然它有效,但它会降低性能.因为php是服务器端脚本,而javascript是用户端.
例子:
第1步
<?php
   $servername = "localhost";
   $username = "";
   $password = "";
   $dbname = "";
   $conn = new mysqli($servername, $username, $password, $dbname);
   if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
   } 
   $sql = "SELECT id, name, image FROM phone";
   $result = $conn->query($sql);
   while($row = $result->fetch_assoc()){ 
      $v[] = $row;    
   }
  echo json_encode($v);
  $conn->close();
?>
第2步
function showUser(fnc) {
   var xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         // STEP 3    
         var p = JSON.parse(this.responseText);
      }
   }
}
myPlugin.start($val); // Tried this, didn't work
它不起作用,因为$val就javascript而言是未定义的,即.php没有输出任何内容$val.尝试在浏览器中查看源代码,您将看到以下内容:
myPlugin.start(); // I tried this, and it didn't work
和
<?php myPlugin.start($val); ?> // This didn't work either
这不起作用,因为php将尝试将其myPlugin视为常量,当失败时它将尝试将其视为'myPlugin'将尝试与php函数的输出连接的字符串,start()因为这是未定义的,它将产生致命的错误
和
 myPlugin.start(<?=$val?> // This works sometimes, but sometimes it fails
虽然这很有可能工作,因为php生成带有预期参数的有效javascript,如果失败,很可能是因为myPlugin尚未准备好.检查您的执行顺序.
另外你应该注意到php out put是不安全的,应该过滤掉 json_encode()
编辑
因为我没有注意到缺少的括号myPlugin.start(<?=$val?>: -  \
正如@Second Rikudo指出的那样,为了正常工作,$val需要包含右括号,例如:$val="42);" 
这意味着php现在将生成myPlugin.start(42);并在javascript执行时按预期工作
这是我没有看到发布的选项。它类似于使用 Ajax,但明显不同。
首先,将脚本的源直接设置为 PHP 文件。
<script type="text/javascript" src="url_to_your_php_file.php" /></script>
您甚至可以将变量传递回 PHP 文件,例如以下示例:
<script type="text/javascript" src="url_to_your_php_file.php?var1=value1" /></script>
然后在“your_php_file.php”中:
<?php
    // THIS IS A SIMPLE EXAMPLE
    // it demonstrates one method of using the src attribute to link
    // to a PHP file which can generate JavaScript code dynamically
    // and share data between PHP and JavaScript
    // you may take this learning example and develop it further
    // relying on your own coding skills for validating data
    // and avoiding errors, of course
    header('content-type: text/javascript');
    // If you pass a $_GET variable from the JavaScript
    // you should add code to validate your $_GET variable(s)
    // You can add code to query a database
    // using $_GET['var1'] or some other criteria
    // You can add simple variable assignments
    $value = 'some value';
    // For the OP's needs (assumes the class object has been defined)
    $val = $myService->getValue();
?>
function name() {
    // Pay attention because you need to use quotes properly
    // and account for possible quotes in the variable strings
    // to avoid both PHP and JavaScript errors
    // example assumes $val has been returned as a string
    // validate $val as needed using your method of choice
    var example1 = "<?php echo addslashes( $val ); ?>";
    var example2 = "<?php echo "he said \\"the value\\""; ?>";
    alert( example1 + ' / ' + example2 );
}
<?php
    // You may even want to include additional files (.php or .js, etc.)
    @include 'local_path_to_some_other_js_file.js';
    @include 'local_path_to_some_other_php_file.php';
    exit;
?>
小智 6
这是技巧:
这是使用该变量的“PHP” :
<?php
    $name = 'PHP variable';
    echo '<script>';
    echo 'var name = ' . json_encode($name) . ';';
    echo '</script>';
?>
现在您有一个名为 的 JavaScript 变量'name',下面是使用该变量的 JavaScript 代码:
<script>
     console.log("I am everywhere " + name);
</script>
小智 5
我已经提出了一种使用PHP分配JavaScript变量的简单方法.
它使用HTML5数据属性来存储PHP变量,然后在页面加载时将其分配给JavaScript.
完整的教程可以在这里找到
例:
<?php
    $variable_1 = "QNimate";
    $variable_2 = "QScutter";
?>
    <span id="storage" data-variable-one="<?php echo $variable_1; ?>" data-variable-two="<?php echo $variable_2; ?>"></span>
<?php
她是JS代码
var variable_1 = undefined;
var variable_2 = undefined;
window.onload = function(){
    variable_1 = document.getElementById("storage").getAttribute("data-variable-one");
    variable_2 = document.getElementById("storage").getAttribute("data-variable-two");
}
| 归档时间: | 
 | 
| 查看次数: | 721806 次 | 
| 最近记录: |