将localStorage值传递给php

时间:2015-08-02 22:27:49

标签: javascript php ajax html2canvas data-uri

我有一个生成图表的页面。我有一个按钮,为它生成一个pdf报告。我想创建此图表的图像并将其插入到pdf中。要创建图像,我使用html2canvas并获取我存储在localstorage中的dataurl。

chart.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type="text/javascript">
   $(document).ready(function() {
        $('#download').click(function() {
             $.ajax({
                type: "POST",
                url: "pdfGen.php",
                data: 'hello',
                success: function(data) {
                    alert("hi");
                }
              });
         });
   }); //END $(document).ready()
</script>

<script>
  //<![CDATA[
  (function() {
     window.onload = function(){
         html2canvas(document.getElementById('chart'), {
              "onrendered": function(canvas) {
                   var img = new Image();
                   img.onload = function() {
                       img.onload = null;
                       console.log(canvas.toDataURL("image/png"));
                       window.localStorage.setItem("imgURL", canvas.toDataURL("image/png"));
                   };
                   img.onerror = function() {
                       img.onerror = null;
                       if(window.console.log) {
                           window.console.log("Not loaded image from canvas.toDataURL");
                       } else {
                           //alert("Not loaded image from canvas.toDataURL");
                       }
                   };
                   img.src = canvas.toDataURL("image/png");
               }
            });
         };
     })();
//]]>
</script>    
<body>
   <a href="pdfGen.php" id="download" class="button">Report</a> 
   ..more code to generate the chart
</body>

下载按钮调用pdfGen.php脚本,该脚本使用fpdf生成报告。 pdfGen.php

<?php
    echo $_POST['data']; //gives error
    /*$pdf = new FPDF();
    $pdf->AddPage();

    //over here I want to add the image from the chart.php page whose data url is now in the localstorage.
    ..more code to generate report
    $pdf->output();*/
 ?>

如何在php脚本中获取图像?我尝试进行ajax调用,但我在pdfGen.php脚本中得到undefined index data。我收到了警报HI但无法获取服务器上的数据。 它似乎不起作用。

2 个答案:

答案 0 :(得分:1)

您的ajax通话错误。

您的通话应该像这样在hello变量/键

中获取值data
$('#download').click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "pdfGen.php",
       data: 'data=hello',
       success: function(data) {
           alert("hi");
       }
   });
});

要详细了解jQuery Ajax,请参阅此link

答案 1 :(得分:0)

这是一个将localstorage从js传递到php会话的示例,假设使用jQuery作为ajax请求者。

<强> 处理

在root中,添加文件: retrieve.php (这将是 RETRIEVE AND SYNC localstorage from js with session from php)

<?php

session_start();
$key = 'my-car'; // Your localstorage key
$client = (isset($_GET[$key]) && $_GET[$key] !== 'null') ? $_GET[$key] : null;
$server = isset($_SESSION[$key]) ? $_SESSION[$key] : null;
$_SESSION[$key] = $client; // Now stored in php´s session variable $_SESSION['my-car']

echo $client === $server ? 'true' : 'false'; // Tells js to reload if data was not synced

<强>

index.html / index.php 中添加以下脚本:(这将 PASS localstorage转换为php并重新加载,如果之后未同步php的会话数据已设置)

<?php
  session_start(); // Dont forget this line
  $key = 'my-car';
  if (isset($_SESSION[$key]) && $_SESSION[$key] !== null) {
     $car = json_decode($_SESSION[$key], true);
     echo $car['name']; // Will print 'Tesla'
  }
?>
<script>
  // Set in JS
  var key = '<?php echo $key; ?>';
  window.localStorage.setItem(key, JSON.stringify({
    name: 'Tesla'
  })); // Set to whatever you want
  var data = {};
  data[key] = window.localStorage.getItem(key);
  // Passes to PHP using GET
  jQuery.get(
    location.protocol + '//' + location.host + '/retrieve.php',
    data
  ).done(function (synced) {
    if (synced !== 'true') {
      // If not synced, reload
      location.reload();
      // Caution! If it doesnt sync correctly, infinite loop may occure
    }
  });
</script>

<强> 使用

最后,将会话从PHP传递到js中的localstorage - &gt;

ANY php文件中:

<?php

start_session();
$key = 'my-car';

if (isset($_SESSION[$key]) && $_SESSION[$key] !== null) {
   // Print old value
   $car = json_decode($_SESSION[$key], true);
   echo $car['name']; // 'Tesla'

   // Update object
   $car['name'] = 'Honda';
   $_SESSION[$key] = json_encode($car);

   // Pass to js:
   echo "<script>window.localStorage.setItem('" . $key . "', '" . $_SESSION[$key] . "');</script>";

   // Prints the updated object with name 'Honda'
   echo "<script>console.log(window.localStorage.getItem('" . $key . "'))";
 }

注意:'my-car'可以用你自己的钥匙替换。