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 微带串馈天线阵列每个阵元宽度计算
  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了