[英]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.