javascript - 使用jquery将php数组发送到外部页面

标签 javascript php jquery

我有一个 PHP 页面来创建一个名为 $results 的多维数组。

我愿意:

  1. 捕获表单按钮的提交
  2. 使用 jQuery 覆盖提交的默认行为
  3. 使用 $.post 在单独的 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()永远不会触发,也不会传递任何数据到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 编码值。但从那里不确定为什么其余的 javascript 不运行;警报永远不会触发,JSON 数据也不会被传递?

你能明白为什么这不起作用吗?

最佳答案

您的 PHP 提供的 json 未作为 JavaScript 变量存储在您的 js 中。

$(document).ready(function(){ 
    var json_results = <?php echo $json_results; ?>;

...

关于javascript - 使用jquery将php数组发送到外部页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8359771/

相关文章:

javascript - 从电子表格名称获取电子表格 ID 或 url

PHP 选择同一行 3 次?

php - MySQL 服务器消失了 haProxy 不断出现错误

php - Docker 无法使用 PHP 连接到 mariadb

javascript - 如何在 DOM `data` 属性中定义一个 JSON 对象?

javascript - 取消 google plus 登录按钮

javascript - 从对象数组中获取具有总和的不同项目

javascript - 在带有视频的函数中使用 Canvas 和 Drawimage

javascript - HTML5 文件上传输入 - onChange

javascript - 这个参数是如何进入被调用函数的?