我正在尝试根据用户的输入(日期选择)生成一些发票。事情是这样的:
invoice.php
文件允许用户从表单中选择一个日期,并根据该选择,同一页面上的发票内容(如金额、客户等)将通过 Ajax 进行更新。ajaxInvoice.php
将生成一个 MySQL 查询,并最终根据日期选择和商家(唯一行)创建一个包含相应表行的数组。
invoice.php
...
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('field_1');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var date = document.getElementById('date').value;
var merchant = document.getElementById('merchant').value;
var queryString = "?date=" + date + "&merchant=" + merchant;
ajaxRequest.open("GET", "ajaxInvoice.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
...
<form name="invoiceDate">
<input type="hidden" id="merchant" value="<?php echo $merchant; ?>" />
Date: <select id="date">
<option>2013-07-23</option>
<option>2013-07-25</option>
</select>
<input type="button" onclick="ajaxFunction()" value="Select Date" />
</form>
...
<div id="field_1">FIELD 1</div>
...
<div id="field_2">FIELD 2</div>
...
<div id="field_3">FIELD 3</div>
...
<小时/>
ajaxInvoice.php
include_once('includes/db.php');
$merchant = $_GET['merchant'];
$date = $_GET['date'];
$merchant = mysql_real_escape_string($merchant);
$date = mysql_real_escape_string($date);
$query = "SELECT * FROM settlements WHERE datePayment = '$date' AND merchant = '$merchant'";
$result = mysql_query($query) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
<小时/>
我想知道我是否可以通过这种方式访问该数组:
echo $array[0]['fieldName'];
并根据不同的行字段更新页面上选定的元素。不确定是否 getElementById
或getElementByName
应该使用。
我的问题是如何实际访问脚本部分以及页面其余部分中的 php 数组,以便我可以在用户选择后使用从数据库查询获得的相应数据来更新各种 div 元素表格中的日期。
事实上,如果只需要更新一个div,代码就可以正常工作,但我不知道如何扩展逻辑来更新多个div。
任何有关语法或代码逻辑的帮助或提示将不胜感激。
提前非常感谢您!
最佳答案
我通常使用 JSON:
服务器上的 PHP:echo json_encode($array)
客户端上的 JavaScript:var response = JSON.parse(ajaxRequest.responseText)
实现:
发票.php
...
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var response = JSON.parse(ajaxRequest.responseText);
// Now you can use:
response[0]['fieldName'];
// Like this
var ajaxDisplay = document.getElementById('field_1');
ajaxDisplay.innerHTML = response[0]['field_1'];
}
}
...
ajaxInvoice.php
...
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
// Encode to JSON
echo json_encode($array);
关于php - 通过 Ajax 从 PHP 数组结果更新多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17886689/