[英]php array to external page using jquery
我有一个php页面来创建一个称为$results
的多维数组。
我想要:
我有这个目前无法使用,并且不确定为什么吗?:
<form id='download_to_excel' method="post">
<input type="image" name="submit" value="submit" id='xls_download_button' src='images/common/buttons/download.png'>
</form>
<?php
$json_results = json_encode($results);
?>
<script type='text/javascript'>
$(document).ready(function(){
alert($json_results);
$("#xls_download_button").click(function(e){
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
});
</script>
选择xls_download_button
, alert()
不会触发,也不xls_download_button
任何数据传递到export_data_to_excel.php
export_data_to_excel.php文件具有以下内容:
<?php
$results = json_decode($_POST['json_data']);
#include the export-xls.class.php file
require_once('export-xls.class.php');
$date = date('Y-m-d');
$filename = "contacts_search_$date.xls"; // The file name you want any resulting file to be called.
#create an instance of the class
$xls = new ExportXLS($filename, $results);
#lets set some headers for top of the spreadsheet
$header = "Searched Contact Results"; // single first col text
$xls->addHeader($header);
#add blank line
$header = null;
$xls->addHeader($header);
$header = null;
$row = null;
foreach($results as $outer){
// header row
foreach($outer as $key => $value){
$header[] = $key;
}
// Data Rows
foreach($outer as $key => $value){
$row[] = $value;
}
$xls->addRow($header);//add header to xls body
$header = null;
$xls->addRow($row); //add data to xls body
$row = null;
}
# You can return the xls as a variable to use with;
# $sheet = $xls->returnSheet();
#
# OR
#
# You can send the sheet directly to the browser as a file
#
$xls->sendFile();
?>
我确实知道$json_results
在回$json_results
确实显示了正确的JSON编码值。 但是从那里不能确定为什么其余的javascript无法运行。 警报永远不会触发,JSON数据也不会传递?
您知道为什么这行不通吗?
PHP提供的json不会作为javascript变量存储在js中。
$(document).ready(function(){
var json_results = <?php echo $json_results; ?>;
...
现在,您只需设置一个名为$results
的php变量,就需要将它转换为JavaScript。
<script type="text/javascript">
// set javascript variable from php
var $results = "<?php echo json_decode($json_data); ?>";
</script>
此代码不应运行:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
它是无效的( ;
不属于此处)。 试试这个代码:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results});
}
确保您的JavaScript代码有错误(您没有在$ .post之后关闭括号),应为:
$(document).ready(function() {
alert($json_results);
$("#xls_download_button").click(function(e) {
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls() {
$.post('./libs/common/export_data_to_excel.php', {
json_data: json_results
});
}
});
然后,您应该将JSON分配给document.ready中的javascript变量
$(document).ready(function() {
var json_results = <?php echo($json_results);?>;
您不能像这样将PHP变量传递给JavaScript:生活在完全不同的世界中。 使用Ajax从JS获取JSON数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.