我遇到了一个问题。
我有这段代码来创建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"],
];
有人能帮我吗?非常感谢。抱歉英语不好,可能很难理解
我不能很好地理解你需要什么。您的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.
首先,从PHP文件中删除script
标记。它的输出应该与您的位置类似。js.
如果在那之后仍然不起作用,则可能需要设置Content-Type
标头。在PHP文件的顶部添加:
header('Content-Type: text/javascript');
在任何内容被发送到输出流之前,这一行应该是。