dongping1689 2011-03-30 02:33
浏览 46
已采纳

如何从JavaScript访问我的PHP变量?

  • Starred lines represent places where problem may be occurring due to my lack of knowledge of how HTML, JavaScript, and PHP interact

Here's the situation:

I'm creating a game that uses JavaScript, and I'm trying to access player information (player's name) from a database using PHP. In order to help me debug I'm not currently trying to access the database. Right now I'm just placing a variable within the PHP file to represent the information I'll try to access in the future, a string, which is the player's name. Access to the HTML file, JavaScript file, and PHP file goes as follows:

*Files are all kept on GoDaddy hosting in the same directory, the files being named:

index.html

milktruck.js

xml_http_request.php

.

The user visits the website, which accesses the JavaScript file using the following line of code:

    <script type="text/javascript" src="milktruck.js"></script>

The game starts and the user is presented with a game interface. At this point the user has not specified to enter multiplayer mode and therefore the line of JavaScript code that accesses the PHP variable and displays it has not fired.

*Nowhere in my JavaScript file or HTML file do I make reference to my PHP file, such as the reference made to the JavaScript file in the HTML file. Do I need to make reference to the PHP file? Does using xml_http_request.php make any difference?

I've tried adding the following line of code in my JavaScript file:

    var simple = '<?php echo $simple; ?>';

and the following in my PHP file:

    $simple = 'simple string';

but when I run the game and click on multiplayer mode instead of the string 'simple string' being displayed the string "php echo $simple;" is displayed (with all the other characters, Stack Overflow won't let me put it in there). JavaScript is recognizing that PHP code as a string, not a line of code.

What's wrong here?

Here's a link to my game if you want to see for yourself. Just click on the "multiplayer mode" button below the screen.

http://alterearth.net

  • 写回答

5条回答 默认 最新

  • dongshuming7131 2011-03-30 02:36
    关注

    You can make the PHP code echo the Javascript code with the variable in it.

    Example:

    echo "<script> var x = $variable; </script>";

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条