简体   繁体   English

将数据数组从PHP发送到JavaScript

[英]Send arrays of data from PHP to JavaScript

I want to send three arrays of data namely vertexa , vertexb and edge_id to HTML page including JavaScript so as to run an algorithm Dijkstra on the vertices. 我想向包括JavaScript的HTML页面发送三个数据数组,分别是vertexavertexbedge_id ,以便在顶点上运行算法Dijkstra。 Should I use JSON commands for this? 我应该为此使用JSON命令吗?

You'll want to use json_encode on the data, like 您将需要在数据上使用json_encode ,例如

<?php
$arr=array('cow'=>'black','feet'=>4);
$encoded=json_encode($arr);

$encoded is now {"cow":"black","feet":4} , which JavaScript can work with. $ encoded现在是{"cow":"black","feet":4} ,JavaScript可以使用。 To send this to a page do 将此发送到页面

header('Content-Type: application/json');  
echo $encoded;

header has to happen before you output anything to the page, even a space or blank line, or PHP will give an error. 标头必须在将任何内容输出到页面(包括空格或空行)之前发生,否则PHP将给出错误。

After generating the data as a PHP array, to output it to JS on the initial page load, you can print it out as the following. 在将数据生成为PHP数组之后,要在初始页面加载时将其输出到JS,可以按以下方式将其打印出来。 Not you don't need to output a special header in this case; 在这种情况下,您不需要输出特殊的标头。 it's part of your normal text/html document. 它是普通text / html文档的一部分。 The header is for an Ajax return. 标头用于Ajax返回。

<?php
$json_data=json_encode($your_array);
?>
<script>
   var an_obj=<?php echo $json_data;?>;
</script> 

Use datatype:"json" for data and datatype:"script" to set the data type for your ajax calls. 使用datatype:"json"表示数据,使用datatype:"script"设置ajax调用的数据类型。

On the servers side set content-types to application/json and application/javascript , respectively. 在服务器端,分别将内容类型设置为application/jsonapplication/javascript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM