简体   繁体   English

无法从PHP到Javascript获得价值

[英]Cannot get value from PHP to Javascript

So in my PHP file I create a JSON Object which I need to get to my Javascript file for processing. 因此,在我的PHP文件中,我创建了一个JSON对象,我需要将其转到Javascript文件进行处理。 I can't seem to transfer anything however, not even with a simple string like this:- 但是,我似乎无法传输任何内容,即使使用这样的简单字符串也是如此:

index.php 的index.php

<?php
  $cookie= "blueberry cake";
?>;

script.js 的script.js

   var details = "<?php echo $cookie; ?>";
   function myFunction() { 
        document.getElementById("demo").innerHTML = details;
   }

index.html 的index.html

<html>

<head>
    <script src="script.js"></script>
    <title>antgus</title>
</head>
<body>

    <h1>Welcome to my page! </h1>

    <button type="button" onclick="myFunction()">Try it</button>

    <p id="demo">A Paragraph.</p>


</body>

I got a button in my HTML, so when I press it the function myFunction get's called. 我在HTML中有一个按钮,因此当我按下按钮时,就会调用myFunction get函数。 It's supposed to change ap element with id "demo" to the string "blueberry cake" 应该将ID为“ demo”的ap元素更改为字符串“ blueberry cake”

Any idea what I'm doing wrong here? 知道我在做什么错吗?

EDIT 编辑

I now have it working except one thing, I can't pass a JSON object to a function i Javascript. 我现在可以正常工作,除了一件事,我无法将JSON对象传递给Javascript函数。 The console throws an error saying that the arguments is wrong, it thinks I am passing multiple strings. 控制台抛出一个错误,指出参数错误,它认为我正在传递多个字符串。 index.php 的index.php

    <?php
    $test = "blue";
    $logLines = file('../../../home/shares/flower_hum/humid.log');
    $entries = array_map("clean",$logLines);
    $finalOutput = [
        'humid'   => $entries
    ];
    function clean($string){
        return json_decode(rtrim(trim($string),','),true);
    }

    $json = json_encode($finalOutput, JSON_UNESCAPED_SLASHES);
    echo $json; //displays valid JSON, I have checked it.
?>

<html>
    <head>
        <script src="script.js"></script>
        <title>antgus</title>
    </head>
    <body>
        <p>Welcome to my page! Down below you can see the data:</p>
        <button type="button" onclick='myFunction("<?php echo $json ?>")'>Try it</button>
        <p id="demo">A Paragraph.</p>
    </body>
</html>

script.js 的script.js

function myFunction(jsonObject) {
    document.getElementById("demo").innerHTML = "INCOMING DATA:";
    alert(jsonObject);
}
    enter code here

The external js file will not be parsed as php meaning that you cannot access that variable. 外部js文件不会被解析为php,这意味着您无法访问该变量。 You can save your js as php (NOT RECOMMENDED). 您可以将js保存为php(不推荐)。 alternatively a) 或者a)

include that function at the bottom of the bottom of the php page: 在php页面底部的底部添加该函数:

<?php
  $cookie= "blueberry cake";
?>;
    //js further down the same page
  <script>
    var details = "<?php echo $cookie; ?>";
   function myFunction() { 
        document.getElementById("demo").innerHTML = details;
    }
 </script>

or b) declare a global variable in the php page so that the external js can access it: 或b)在php页面中声明一个全局变量,以便外部js可以访问它:

//php page
    <?php
      $cookie= "blueberry cake";
    ?>;
<script> var details = "<?php echo $cookie; ?>";</script>


//js file
       function myFunction() { 
          //details will be accessible since it has been declared in the global space of the index.php page
            document.getElementById("demo").innerHTML = details;
       }

This should work perfectly: 这应该工作完美:

With In-Document JS: 使用文档内JS:

<?php
     $cookie= "blueberry cake";
?>;

<html>

    <head>
        <script type="text/javascript">
            var details = "<?php echo $cookie; ?>";
            function myFunction() {
                document.getElementById("demo").innerHTML = details;
            }
        </script>
        <title>antgus</title>
    </head>
    <body>

        <h1>Welcome to my page!</h1>
        <button type="button" onclick="myFunction()">Try it</button>
        <p id="demo">A Paragraph.</p>
    </body>

With External JS: 使用外部JS:

<?php
     $cookie= "blueberry cake";
?>;

<html>

    <head>
        <script type="text/javascript">
            var details = "<?php echo $cookie; ?>";
        </script>
        <script type="text/javascript" src="script.js"> </script>
        <title>antgus</title>
    </head>
    <body>

        <h1>Welcome to my page!</h1>
        <button type="button" onclick="myFunction()">Try it</button>
        <p id="demo">A Paragraph.</p>
    </body>

script.js File: script.js文件:

    function myFunction() {
         // HAS ACCESS TO details WHICH IS ON THE GLOBAL SCOPE
         document.getElementById("demo").innerHTML = details;
    }

使用json_encode编码json对象,即

<script> var details = "<?php echo json_encode($cookie); ?>";</script>

Things to consider:- 要考虑的事情:

1.External js will not work as you tried. 1,外部js无法像您尝试的那样工作。

2.When you call a javascript function directly through onclick code then you have to pass data also for working further. 2.当您直接通过onclick代码调用javascript函数时,还必须传递数据以进一步工作。

A working code sample:- 工作代码示例:-

index.php:- index.php文件: -

<?php
  $cookie= "blueberry cake";
?>
<html>

<head>
    <script src="script.js"></script>
    <title>antgus</title>
</head>
<body>
<h1>Welcome to my page! </h1>

<button type="button" onclick='myFunction("<?php echo $cookie; ?>")'>Try it</button>

<p id="demo">A Paragraph.</p>

script.js:- 的script.js: -

function myFunction(details) { 
    document.getElementById("demo").innerHTML = details;
}

Output at my local end:- 输出在我的本地端:

before click:- http://prntscr.com/ci94s9 点击之前: -http : //prntscr.com/ci94s9

After click:- http://prntscr.com/ci94w9 单击后: -http : //prntscr.com/ci94w9

Remove the quotes around php, dude. 删除php周围的引号,老兄。 You are assigning string instead of the php variable value. 您正在分配字符串而不是php变量值。

var details = "'" + <?php echo $cookie; ?> + "'";

This will assign the actual $cookie value instead of the string '<? php echo $cookie; ?>' 这将分配实际的$cookie值,而不是字符串'<? php echo $cookie; ?>' '<? php echo $cookie; ?>' '<? php echo $cookie; ?>' . '<? php echo $cookie; ?>'

The php-script is run server-side, and the javascript is run client-side, and the two do not share some kind of scope. php-script在服务器端运行,而javascript在客户端运行,两者不共享某种范围。

In other words, the $cookie variable is assigned a value in php, but it isn't used. 换句话说, $cookie变量在php中分配了一个值,但未使用。 Then you use a variable in your javascript with the same name (but completely unrelated to the php variable), but since it is never assigned anything, it's undefined . 然后,您在javascript中使用具有相同名称的变量(但与php变量完全无关),但是由于从未分配任何变量,因此undefined

gavgrif offers some solutions to fix this. gavgrif提供了一些解决方案来解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM