2017-09-15 70 views
-5

我无法修改函数内部的全局变量,也无法在浏览器上显示回显消息。请帮我为什么我无法在浏览器上回显任何内容

<!DOCTYPE html> 
<html> 
<body> 
    <?php 
    $response = array(); 
    function() { 
     global $response['res']="hello"; 
     echo json_encode($response); 
    } 
    echo "hello"; 
    ?> 

    </body> 
    </html> 
+0

你的代码没有按” t回声,因为它不能运行,因为它不能编译。 'global $ response ['res'] =“hello”;'是两个语句合并成一次(这不起作用)。尝试'全球$回应; $ response ['res'] =“hello”;' – axiac

+0

您需要为您的函数命名并移除'global $ response [...]'。 – Script47

+0

语法错误:response ['res'] =“hello”; '$' – Priya

回答

0

我已经清理你的代码一点点,加一个名字的功能,现在我看到hello在浏览器中。该功能还需要return而不是回显,因为您可以回显功能,如echo test()。这应该排序您的问题:

<?php 
$response = array(); 
function test() { 
    global $response; 
    $response['res'] = "hello"; 
    return json_encode($response); 
} 
echo test(); 
?> 

完整的HTML代码,应放置在一个.php文件:

<!DOCTYPE html> 
<html> 
    <body> 
     <?php 
      $response = array(); 
      function test() { 
       global $response; 
       $response['res'] = "hello"; 
       return json_encode($response); 
      } 
      echo test(); 
     ?> 
    </body> 
</html> 

并在浏览器输出:

enter image description here

+0

我将文件保存为xyz.html并插入了已写入的确切代码,但我没有在浏览器中获得任何输出, –

+0

<!DOCTYPE html> <?php $ response = array(); function test(){ global $ response; $ response ['res'] =“hello”; return json_encode($ response); } echo test(); ?> 这是我整个代码 –

+1

那么你不会,如果你已经保存为'.html'这个代码工作,因为我已经在当地进行了测试。您可能有其他代码阻止它。创建一个新的'.php'文件,你会看到JSON数据 –

相关问题