将数据数组从php发送到javascript

时间:2010-11-27 08:19:21

标签: php javascript html ajax json

我的jphp.php文件包含以下内容:

<?php

$send_array = array();
$edge_number = array('a','b');

$vertex_a = array('c','d');

$send_array[0] = $edge_number;
$send_array[1] = $vertex_a;

echo json_encode($send_array);

?>

我的javascript文件包含以下内容:

<html>
<head>
<script language="javascript">
function postRequest(strURL)
{
    var xmlHttp;
    if(window.XMLHttpRequest)
    { // For Mozilla, Safari, ...
        var xmlHttp = new XMLHttpRequest();
    }
    else if(window.ActiveXObject)
    { // For Internet Explorer
        var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttp.open('GET', 'jphp.php', true);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttp.onreadystatechange = function()
    {
        if (xmlHttp.readyState == 4)
        {
    var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );       updatepage(xmlHttp.responseText);
        }
    }
    xmlHttp.send('jphp.php');
}

function updatepage(str)
{
    document.write(str);
}



var vertex_a = new Array();
var edge_number = new Array();
var rec_array = new Array();
rec_array = {"edge_number", "vertex_a"};
//rec_array[1] = names;
for(var i=0;i<1;i++)
{
    document.write(rec_array[i]);
}
$.ajax({
  url: 'jphp.php'
  type: 'post', // post or get method
  data: {}, // if you need to pass post/get parameterds you can encode them here in JSON format
  dataType: 'json', // the data type you want returned... we will use json
  success: function(responseData) {
    alert('edge_number='+responseData[0].join(','));
    alert('vertex_a='+responseData[1].join(','));
  }
});

我已经在php中编码数据数据....现在我想将这两个数据数组发送到javascript .....我不知道要使用的正确命令。我在谷歌搜索时感到困惑。

请帮忙。

3 个答案:

答案 0 :(得分:0)

JavaScript通过AJAX调用PHP,然后当它获得响应时,它使用JSON.parse()将JSON字符串转换为JavaScript对象。

答案 1 :(得分:0)

在客户端,我建议使用jQuery,它是$.parseJSON()函数 您可以使用$.get()$.post()$.ajax()进行AJAX通话。请参阅文档了解其用法。

在服务器端,使用PHP本机json_encode()函数对数组进行编码 然后设置正确的HTTP标头(!!!)

header('Content-type: application/json');

并回显JSON编码数据=]

答案 2 :(得分:0)

使用jquery的简单特定示例:

javascript页面:

$.ajax({
  url: 'url/of/page.php'
  type: 'post', // post or get method
  data: {}, // if you need to pass post/get parameterds you can encode them here in JSON format
  dataType: 'json', // the data type you want returned... we will use json
  success: function(responseData) {
    var edge_number = responseData.edge_number;
    var vertex_a= responseData.vertex_a;
    var rec_array = responseData;
  }
});

在你的php中:

$send_array = array(
  'edge_number' => array('a','b'),
  'vertex_a' => array('c','d')
); 

header('Content-type: application/json');
echo json_encode($send_array);