2013-08-09 2 views
0

HandsOnTable을 사용하여 서버의 JSON 파일에 저장을 구현하려고합니다. 나는 또한 JSON 파일에 위의 모든 셀의 데이터를 작성하는 PHP 스크립트에서 일하고 있어요JSON에 HandsOnTable 데이터 자동 저장

var handsontable = $container.data('handsontable'); 

$parent.find('button[name=save]').click(function() { 
    $.ajax({ 
    url: "save.json", 
    data: {"data": handsontable.getData()}, //returns all cells' data 
    dataType: 'json', 
    type: 'POST', 
    success: function (res) { 
     if (res.result === 'ok') { 
     $console.text('Data saved!'); 
     } 
     else { 
     $console.text('Save error'); 
     } 
    }, 
    error: function() { 
     $console.text('Save error.'); 
    } 
    }); 
}); 

:

<div id="example1" class="handsontable"></div> 
<button name="save">Guardar</button> 

그리고 jQuery를 :

이 같은 페이지 모습입니다 사용자가 저장 버튼을 클릭 할 때마다 호출되어야합니다. 이게 어떻게 보이는지 지금은 :

제 질문은 어떻게 PHP 변수 $ stringData에 모든 셀의 데이터를 보냅니 까?

미리 감사드립니다.

답변

0
  1. 'url : "save.json",'ajax에서 의미가 없습니다. url은 게시 된 데이터가 PHP에서 처리되는 장소 여야합니다.
  2. 데이터 : { "data": handsontable.getData()}, (handsontable.getData()의 형식이 확실하지 않습니다) ... 게시하기 전에 json 형식의 문자열을 만들어야 할 수 있습니다.
  3. PHP 코드에서 try '$ stringData = $ _POST [ "data"];' 또는 json_encode를 사용하여 파일에 저장하기 전에 json 형식의 문자열을 만드십시오.
+0

안녕 방법을 다음 간다, I "save.json"을 "escreve.php"로 바 꾸었습니다. PHP는 빈 "testFile.json"을 생성합니다. 따라서 스크립트는 실행 중이지만 handsontable의 데이터는 전송되지 않습니다. 당신의 도움을 주셔서 감사합니다! –

+0

안녕하세요, 나를 위해 일했습니다 :

2

나는 당신이하고 싶은 것과 똑같은 것을 가지고있다. 나는 Ajax와 자동 완성 기능으로 이것을 구현했다. 새로운 데이터를 load.json 파일에 직접 넣으므로로드 버튼을 누른 사용자가 새 데이터를 가져올 때마다. 내 코드는 ...

index.html을

<script data-jsfiddle="example"> 
var $console = $("#example1console"); 
     var data = [ [] ]; 
     var autosaveNotification; 

      $('#example').handsontable({ 
       data: data, 
       minSpareRows: 1, 
       minSpareCols: 1, 
       colHeaders: true, 
       rowHeaders: true, 
       autoWrapRow: true, 
       currentRowClassName: 'currentRow', 
       currentColClassName: 'currentCol',    
       contextMenu: { items: { 
             "row_above": {}, 
             "row_below": {}, 
             "hsep1": "---------", 
             "col_left": {}, 
             "col_right": {}, 
             "hsep2": "---------", 
             "remove_row": {}, 
             "remove_col": {} 
             } 
          }, 

       afterChange: function (change, source) 
          { 
           if (source === 'loadData') { 
            return; //don't save this change 
           } 
           if ($('input[name=autosave]').is(':checked')) 
           { 
            clearTimeout(autosaveNotification); 

            $.ajax({ 
            url: "saveData.php", 
            dataType: "json", 
            type: "POST", 
            data: {"data": handsontable.getData()}, //returns all cells' data 
            complete: function (data) { 
              $console.text('Autosaved (' + change.length + ' cell' + (change.length > 1 ? 's' : '') + ')'); 
              autosaveNotification = setTimeout(function() { 
              $console.text('Changes will be autosaved'); 
              }, 1000); 
             } 
            }); 
           } 
          } 
      });  
     </script> 

saveData.php이 당신을 도울 것입니다

<?php 

$file = 'json\load.json'; 

file_put_contents($file, ""); // Erase file content because we need to use this content for loading. 

    foreach ($_POST['data'] as $change) 
    {  
     file_put_contents($file, json_encode($change) . ",", FILE_APPEND | LOCK_EX); 
    } 

// remove last comma from data... 
$fileHandle = fopen($file, 'r+') or die("can't open file"); 
$stat = fstat($fileHandle); 
ftruncate($fileHandle, $stat['size']-1); 
fclose($fileHandle); 


// Append rest of syntax to file content so when press load next time we got ready new data... 
$current = file_get_contents($file); 
$newData = "{ \"data\": [ " . $current . " ] }"; 
file_put_contents($file, $newData); 

// success json response... 
$out = array('result' => 'ok'); 
echo json_encode($out); 

?> 

희망 ...

+0

물론 도움이됩니다. –