将数组值传递给js [英] Passing array values to js
本文介绍了将数组值传递给js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以目前的设置如下:
PHP:data.php
<?php
$method = $_SERVER['REQUEST_METHOD'];
$data = array(
"16508",
"16498",
"16506"
);
if ($method === "GET") {
echo json_encode($data);
}
?>
JS:
$.get("./page_asset/data.php").then(function(returned) {
data = JSON.parse(returned);
};
现在,如何在不获取特定php页面的情况下解析数据(因为我没有我不想依赖特定的php地址,例如/page-asset/data.php。)
Now, how do I parse the data without getting the specific php page (as I don't want to rely on the specific php address such as "/page-asset/data.php").
例如:
PHP:
<?php
$data = array(
"16508",
"16498",
"16506"
);
?>
我只想将这些值传递给js,而不依赖于页面网址。
I simply want to pass these values to js without relying on the page url.
推荐答案
您可以使用PHP在原始页面中创建Javascript。 json_encode()
可用于转换类似于JS文字的PHP值。
You can use PHP to create the Javascript in the original page. json_encode()
can be used to convert a PHP value to the analogous JS literal.
<?php
$data = array(
"16508",
"16498",
"16506"
);
?>
<script>
var data = <?php echo json_encode($data); ?>;
</script>
这篇关于将数组值传递给js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文