Javascript 如何将关联数组从PHP传递到HTML进行进一步处理
在我的HTML页面上,我有一个通过PHP发送数据库查询的脚本。 现在,我需要将带有结果的数组(关联数组)传递回我的HTML页面,以填充一些文本区域 问题(我是PHP新手): 1-数组可以按原样传递,还是需要编码/解码或序列化/非序列化(以及如何传递) 2-一旦数组到达HTML脚本,我可以通过循环遍历它的元素吗(我的意思是,是否可以在HTML脚本中进行循环?) 3-如果后一种方法不可行,我如何指示PHP在HTML页面上填充给定的文本区域 已编辑(现在使用代码):Javascript 如何将关联数组从PHP传递到HTML进行进一步处理,javascript,php,jquery,html,Javascript,Php,Jquery,Html,在我的HTML页面上,我有一个通过PHP发送数据库查询的脚本。 现在,我需要将带有结果的数组(关联数组)传递回我的HTML页面,以填充一些文本区域 问题(我是PHP新手): 1-数组可以按原样传递,还是需要编码/解码或序列化/非序列化(以及如何传递) 2-一旦数组到达HTML脚本,我可以通过循环遍历它的元素吗(我的意思是,是否可以在HTML脚本中进行循环?) 3-如果后一种方法不可行,我如何指示PHP在HTML页面上填充给定的文本区域 已编辑(现在使用代码): //HTML 函数Populate
//HTML
函数PopulateTextAreas()
{
var arrayTextAreasNames=[“姓名”、“姓氏”、“dob”];
//现在将其传递给php
var xhttp=newXMLHttpRequest();
var jsonstring=JSON.stringify(arrayTextAreasNames);
var encoded=encodeURIComponent(jsonstring);
xhttp.open(“GET”、“LoadFromDb.php?hId=“+”&arrayTextAreasNames=“+encoded,true”);
xhttp.onreadystatechange=函数()
{
if(this.readyState==4&&this.status==200)
{
var decoded=json_decode(this.responseText);
console.log(已解码);//不工作
//随后会出现一个循环来分隔数组的每个元素,然后填充相应的textareas,其方式类似于以下方式:
//document.getElementById(“name”).value=this.responseText;
//document.getElementById(“姓氏”).value=this.responseText;
//document.getElementById(“dob”).value=this.responseText;
}
};
xhttp.send();
}
//PHP
//关联数组构建在如下循环中
$ArrayDbEntryName_及其值[$i][$DbItemName]=$DbItemValue;
//它看起来像下面的一个:
阵列(3){
[0]=>
阵列(1){
[“名称”]=>
字符串(1)“paul”
}
[1]=>
阵列(1){
[“姓氏”]=>
字符串(2)“绿色”
}
[2]=>
阵列(1){
[“dob”]=>
串(8)“1/1/1980”
}
//然后数组像这样回显到HTML页面
$resultstringfied=JSON.stringify($ArrayDbEntryName_和_其值);
echo encodeURIComponent($ResultString-Gified);
1.如果要传递数组,可以使用JSON格式。查看一下
HTML是一种标记语言,而不是脚本。要在浏览器中循环浏览数组,可以使用Javascript。或者可以使用PHP在服务器端生成HTML页面
3.例如:
<?php
/**
* This is .php file
*
* @var array $rows Array of data which you would to show in textarea
*/
?>
<textarea>
<?php
foreach ($rows as $key => $value): ?>
<p id="<?= $key ?>"><?= $value ?></p>
<?php endforeach; ?>
</textarea>
我在想这样的事情:
在PHP方面:
echo '<div id="my_array" style="display:hidden">' . json_encode($myArray) . '</div>';
echo'.json_编码($myArray)。'';
在HTML/JavaScript端:
<script>
var myArray = JSON.parse(document.getElementById("myArray").innerHTML);
//loop through myArray using JavaScript
var arrayLength = myArray.length;
for (var i = 0; i < arrayLength; i++) {
alert(myArray[i]);
//Do something
}
<script>
var myArray=JSON.parse(document.getElementById(“myArray”).innerHTML);
//使用JavaScript遍历myArray
var arrayllength=myArray.length;
对于(变量i=0;i
对于#3,有很多方法。我可能需要查看生成textarea
的代码,以建议如何用文本填充它
更新
我看到您直接使用的是var xhttp=new-XMLHttpRequest();
。为什么
我非常推荐使用jqueryajax工具(简单的学习曲线和低初始投资)或类似AngularJS(高学习曲线和初始投资)的东西来处理AJAX请求
这将是更少的代码和更少的东西调试
对于json\u decode()
无效,请尝试json.parse(this.responseText);
JSON.parse
是JS函数,而JSON\u decode
是PHP函数,您正试图在JS脚本中使用它
我还没有深入研究代码,了解如何将文本放入textarea
框中,但您可以使用AJAX进行操作,并执行以下操作:
编辑:以下信息根据OP(海报代码包含之前)提供
PHP中的数组无法传递到HTML。相反,您可以将该数组转换为更可用的格式,然后发送到HTML。为此,通常使用JSON(Javascript对象表示法)格式。例如,假设您在PHP文件中创建关联数组
$info = ["firstname" => "somename", "age" => 25, "address"=>["home"=>"something1","collage"=>"something2"]];
现在,您必须将$info转换为JSON格式。
你可以使用下面的函数来做这件事
$jsoninfo = json_encode($info);
JSON格式只是由名称-值对组成。名称是“firstname”,它的值是“somename”。这是第一个名称-值对。依此类推。
因为您希望在HTML上显示它,所以您会回显$jsoninfo:
echo$jsoninfo;
这就是它在HTML上的外观
{"firstname":"somename","age":25,"address":{"home":"something1","collage":"something2"}};
但是你说你想在HTML中把它填充到一个textarea中。因此我用这个来代替那个简单的echo。这将创建一个textarea元素,并将整个$jsoninfo值放在这个textarea元素中
echo "<textarea>".$jsoninfo."<textarea>"; // this is not a good practice to send value to HTML like this way, since you asked about it I had to write like that. You will need javascript to actually play with the JSON object and then write it to HTML.
echo.“$jsoninfo.”;//这样将值发送到HTML不是一个好的做法,因为你问过,我不得不这样写。你需要javascript来实际处理JSON对象,然后将其写入HTML。
与数组不同,从JSON中,您必须使用名称-值对中的名称来获取其关联的值。为此,您需要javascript。我向您展示
因为这不是一个关于javascript的教程,所以我直接说
假设您的html页面中也有一个空段落元素(我们需要它),其id为“p1”。如下所示:
<p id='p1'></p>
现在,我们将在HTML内部或外部js文件中使用以下javascript代码,这些代码已经包含在HTML中
<script>
var getfromtextarea = document.getElementsByTagName("textarea")[0].innerHTML; //get the JSON object from textarea and save it into a javascript variable named getfromtextarea
var get2 = JSON.parse(getfromtextarea); //JSON.parse() function is used to convert JSON object into javascript plain object so that we can get the value associated to its name(remember name-value pair), you will understand this is next line.
document.getElementById("p1").innerHTML = get2.firstname; //this will write/print "somename"(without quotes) inside the p element that we had created in HTML.
</script>
var getfromtextarea=document.getElementsByTagName(“textarea”)[0].innerHTML;//从textarea获取JSON对象,并将其保存到名为getfromtextarea的javascript变量中
<script>
var getfromtextarea = document.getElementsByTagName("textarea")[0].innerHTML; //get the JSON object from textarea and save it into a javascript variable named getfromtextarea
var get2 = JSON.parse(getfromtextarea); //JSON.parse() function is used to convert JSON object into javascript plain object so that we can get the value associated to its name(remember name-value pair), you will understand this is next line.
document.getElementById("p1").innerHTML = get2.firstname; //this will write/print "somename"(without quotes) inside the p element that we had created in HTML.
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>PHP HTML - Pass data around with POST</title>
<link rel='stylesheet' type="text/css" href="css/style.css" />
</head>
<body>
<form method="post" name="frmData" action="pass_data_received.php">
Name:<textarea name="name"></textarea>
Surname:<textarea name="surname"></textarea>
Date of birth:<textarea name="dob"></textarea>
<br />
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
// Process only if the form was submitted
if(isset($_POST['submit'])){
echo '<h3>Data was submitted as shown below.</h3>';
// init variable data to an empty array
$data = [];
// set the data to the post array
$data = $_POST;
// get the count of posted by only the name field (any field can do as long as it is a mandatory/required input)
$dataLength = count($data['name']);
/* You can use a (foreach) loop or a (for) loop to iterate through the data array as below methods */
// Method-1: for each loops through each entry in the data array as key->vlue pairs and echo with line break
// Note: This will not give you index for further referencing
foreach($data as $key=>$value){
echo $key.':'.$value.'<br />';
}
// Method-2: for loop
// Note: This will give you index (i) for reference if required
for( $i=0; $i > $dataLength; $i++ ){
$data['name'] = $_POST['name'];
$data['surname'] = $_POST['surname'];
$data['dob'] = $_POST['dob'];
}
// Print_r the array for debug only
echo '<pre>'; print_r($data); echo '</pre>';
?>
<h3>Data received and processed through POST and PHP only</h3>
<!-- Note:
You can post the same data even further to any HTML or PHP again if needed
using the POST and ACTION
-->
<form method="post" name="frmData" action="pass_data_further.php">
Data of index <?php echo $i; ?> <br />
<hr />
Name:<textarea name="name"><?php echo $data['name'] ?></textarea>
Surname:<textarea name="surname"><?php echo $data['surname'] ?></textarea>
Date of birth:<textarea name="dob"><?php echo $data['dob'] ?></textarea>
<br />
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
?>