小编典典

将数据数组从php发送到javascript

ajax

我的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 …我不知道要使用的正确命令。我对谷歌搜索感到困惑。

请帮忙 。


阅读 253

收藏
2020-07-26

共1个答案

小编典典

使用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);
2020-07-26