donglefu6195 2013-05-23 07:56
浏览 42
已采纳

在javascript文件中使用php var错误[重复]

This question already has an answer here:

I have a question about using a php variable in my javascript file. This is my index.php file:

<body>
    <div class="container">
        <div class="row">
            <div class="span12">
                <?php
                    if(isset($_GET['appid'])) {
                        // GET appid
                        $appid = $_GET['appid'];

                        $json_url  ='http://api.url.com/api/gateway/call/1.4/getApp?appid=' . $appid;

                        $ch = curl_init($json_url);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

                        $str = curl_exec($ch);
                        curl_close($ch);

                        $data = json_decode($str);
                        $array = json_encode($data);
                    }  

                    else{

                    }    
                ?>
                <p id="errors" class="text-error"></p>
            </div>
        </div>

        <hr>

    </div> <!-- /container -->

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>

    <script src="js/vendor/bootstrap.min.js"></script>

    <script src="js/plugins.js"></script>
    <script src="js/main.js.php"></script>
</body>

As you can see I check if an appid is sent. When I received it I load data from an api. In the bottom of the page I have a link to my javascript file. (.php because I want to use the php var $ array in my js file)

My main.js.php:

$(document).ready(function() {
    var data = <?php echo $array;?>;
    alert(data);
});

But I got always error in console:

Uncaught SyntaxError: Unexpected token <

Does anyone know what I do wrong?

</div>
  • 写回答

4条回答 默认 最新

  • doson1998 2013-05-23 08:21
    关注

    You are creating the array in a completely different file! The two variables are not in the same scope. What's more, the Javascript file is apparently not interpreted as PHP (and neither should it). So:

    1. Javascript complains about the <? tag, which it should never see.
    2. Even if you solved that, it won't work since there's no PHP $array variable in main.js.php.

    Start by understanding how Javascript and PHP are interpreted, see Reference: Why does the PHP code in my Javascript not work?.

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

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛