简体   繁体   English

将值从php回显到javascript

[英]Echo a value from php to javascript

I have a .js file with only javascript in it and my question is; 我有一个仅包含JavaScript的.js文件,我的问题是; I have separate .php file and .js file. 我有单独的.php文件和.js文件。 And I want to get the value the .php file echoes/returns. 我想获取.php文件echo / returns的值。 How can I fix this? 我怎样才能解决这个问题?

I searched around and found that I could use this: 我四处搜寻,发现可以使用:

php: PHP:

<?php
  echo 'name';  
?>

js: JS:

var user_name;
$.get('getId.php', function(data) {
    user_name = data;
});
// other code

But this didn't work. 但这没有用。 Or perhaps do I need another js lib included? 还是我需要包含另一个js库? I don't get what the php file returns, its blank. 我没有得到什么php文件返回,其空白。

use json_encode(); 使用json_encode();

Add jquery library 添加jQuery库

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

</head>

In PHP 在PHP中

<?php
  echo json_encode(array('name'));  
?>

THEN 然后

    <script type="text/javascript">

    $(document).ready(function(){
        var user_name;
        $.get('getId.php', function(data) {
            user_name = data;
        });

   });   
 </script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){

        $.ajax({
            type: "GET",
            url: "anyfile.php",
            success: function(data){
                alert(data);

            }
        });

        return false;


}); 
</script>

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

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