如何将json数据传递给.js文件

时间:2015-04-03 08:50:38

标签: javascript php json

我在这里遇到了问题。

我有这段代码在locations.php中创建json数据

<?php
    $locations = array(
            array('2479 Murphy Court', "Minneapolis, MN 55402", "$36,000", 48.87, 2.29, "property-detail.html", "assets/img/properties/property-01.jpg", "assets/img/property-types/apartment.png"),
            array('3398 Lodgeville Road', "Golden Valley, MN 55427", "$28,000", 48.866876, 2.309639, "property-detail.html", "assets/img/properties/property-02.jpg", "assets/img/property-types/apartment.png")
        );
?>

<script type="text/javascript">
    var locations = "<?= json_encode($locations) ?>";
</script>

我想将json传递给locations.js。它将由具有getScript功能的另一个.js文件调用。我试着调用locations.php,但它不起作用,所以我创建locations.js进行测试,它的工作原理

不工作

$.getScript("assets/php/locations.php", function(){

工作

$.getScript("assets/js/locations.js", function(){

locations.js

var locations = [
    ['2479 Murphy Court', "Minneapolis, MN 55402", "$36,000", 48.87, 2.29, "property-detail.html", "assets/img/properties/property-01.jpg", "assets/img/property-types/apartment.png"],
    ['3398 Lodgeville Road', "Golden Valley, MN 55427", "$28,000", 48.866876, 2.309639, "property-detail.html", "assets/img/properties/property-02.jpg", "assets/img/property-types/apartment.png"],
];

任何人都可以帮助我吗?谢谢。 抱歉英语不好,也许很难理解

2 个答案:

答案 0 :(得分:2)

我不确定你理解你需要什么。 您的PHP文件需要输出JSON对象: location.php

    <?php

$locations = array(
    array('2479 Murphy Court', "Minneapolis, MN 55402", "$36,000", 48.87, 2.29, "property-detail.html", "assets/img/properties/property-01.jpg", "assets/img/property-types/apartment.png"),
    array('3398 Lodgeville Road', "Golden Valley, MN 55427", "$28,000", 48.866876, 2.309639, "property-detail.html", "assets/img/properties/property-02.jpg", "assets/img/property-types/apartment.png")
);
header('Content-Type: application/json');
die(json_encode($locations));

    ?>

然后你可以用jquery加载它

$.getJSON("location.php", function(data) {
  // do whatever you want with data
  console.log(data);
});

如果要加载location.php输出的脚本

<?php
    $locations = array(
            array('2479 Murphy Court', "Minneapolis, MN 55402", "$36,000", 48.87, 2.29, "property-detail.html", "assets/img/properties/property-01.jpg", "assets/img/property-types/apartment.png"),
            array('3398 Lodgeville Road', "Golden Valley, MN 55427", "$28,000", 48.866876, 2.309639, "property-detail.html", "assets/img/properties/property-02.jpg", "assets/img/property-types/apartment.png")
        );
?>
var locations = <?= json_encode($locations) ?>;

然后你可以通过jQuery.getScript加载它。

答案 1 :(得分:1)

首先,从PHP文件中删除script标记。它的输出应该与您的locations.js类似。

如果之后仍然无效,则可能需要设置Content-Type标题。在PHP文件的顶部添加:

header('Content-Type: text/javascript');

此行应在之前将任何内容发送到输出流。