2013-03-20 53 views
0

我有解碼JSON數據的問題。其實我希望slickgrid工作保存在MySQL中。 所以,我讀[question]:Saving Changes in SlickGrid with php,但不知道如何解碼數據。
jquery解碼json

這裏是我的PHP腳本來處理JSON:

<script src="jquery-1.7.min.js"></script> 
    <script type="text/javascript" src="jquery.json.js"></script> 
    <?php 

    if(isset($_POST['dataz'])) 
    { 
     ?> 
<!--this isn't working--> 
     <script> 
     var obj = $.JSON.decode(input[name='dataz'].val()); 
     alert('json decode : '+obj); 
     </script> 
     <?php 
//this produce nothing 
     echo json_decode($_POST['dataz']); 
     var_dump(($_POST['dataz'])); 
    } 
    else 
    { 
     echo "No data."; 
    } 
    ?> 

,這是我試圖解碼

... 
<form action="proses.php" method="POST"> 
    <input type="submit" value="Save"> 
    <input type="hidden" name="dataz" value=""> 
</form> 
<script> 
    $(function() { 
    $("form").submit(
     function() { 
     $("input[name='dataz']").val($.JSON.encode(data)); 
     } 
    ); 
    }); 
</script> 
+0

如果是*僅*有關如何解析JSON,這是在這裏回答:http://stackoverflow.com/q/4935632/218196。但是,這可能不是你唯一的問題。 – 2013-03-20 09:47:04

+0

你必須專門使用JSON嗎?因爲我用MySQL完成的方式是使用事件'grid.onCellChange.subscribe(function(e,args){$ .post ...'沒有使用任何JSON,儘管我將JSON作爲回調返回問題,如果你需要進一步的幫助,我會發佈一個「答案」 – ghiscoding 2013-03-20 14:47:39

+0

@ghiscoding:你可以分享代碼嗎? – Bari 2013-03-21 01:52:52

回答

0

好吧,這裏是我的插入,更新代碼的JSON,從SlickGrid刪除到MySQL

var ajaxFileURL = "fileAjax.php?action=list"; 

function populateList(ajaxFileURL) {  
    var msgDelete = 'Do you really want to delete the row?'; 
    var deleteIcon = "<img src='/images/delete.png' border='0' />"; 

    // attach the delete event on the ID column 
    var columns = [  
     {id:"id", name:"ID", field:"id", width:8, formatter: function (r,c,id,def,datactx){ return "<a href='#' onclick='if (confirm(\""+msgDelete+"\")) removeClick(\""+ajaxFile+"\",\""+id+"\","+r+")'>"+deleteIcon+"</a>";}}, 
     {id: "title", name: "Title", field: "title", width: 70, minWidth: 50, cssClass: "cell-title", sortable: true, editor: Slick.Editors.Text} 
    ]; 
    var options = { 
     enableCellNavigation: true, 
     editable: true 
    }; 

    $.getJSON(ajaxFileURL, function (ServerResponse) { 
     var groupItemMetadataProvider = new Slick.Data.GroupItemMetadataProvider(); 
     dataView = new Slick.Data.DataView({ 
      groupItemMetadataProvider: groupItemMetadataProvider, 
      inlineFilters: true 
     }); 
     grid = new Slick.Grid("#myGrid", dataView, columns, options); 

     // This section treats the INSERT/UPDATE 
     grid.onCellChange.subscribe(function(e,args) { 
      //dataView.updateItem(args.item.id,args.item); 
      if (typeof(args.item.id)=='undefined') 
       $.post(ajaxFileURL+"?action=insert", args.item); 
      else{ 
       $.post(ajaxFileURL+"?action=update", args.item, function(ServerResponseUpt){ 
        // if database return an error then display it to the user and undo the cell change 
        if(parseInt(ServerResponseUpt.affected_rows) < 1 || ServerResponseUpt.error_msg != "") { 
         alert("UPDATE ERROR: "+ServerResponseUpt.error_msg); 
         args.item[ previousCellNames[0] ] = previousCellValues[0]; 
         grid.updateRow(args.row); 
         grid.updateRowCount(); 
         grid.render(); 
        } 
        previousCellNames = new Array(); 
        previousCellValues = new Array(); 
       }, "json"); 

       // refresh the data on grid 
       grid.updateRow(args.row); 
       grid.updateRowCount(); 
       grid.render(); 
      } 
     }); 
     // initialize the model after all the events have been hooked up 
     dataView.beginUpdate(); 
     dataView.setItems(ServerResponse.data); 
     dataView.endUpdate(); 
    } // end of $.getJSON() 
} // end of populateList() 

// outside function to DELETE 
function removeClick(ajaxFileURL, dbRowId, gridRow) { 
    $.post(ajaxFileURL+'?action=delete', {id:dbRowId}); 
    var item = dataView.getItem(gridRow);//RowNum is the number of the row 
    var rowID = item.id 
    dataView.deleteItem(rowID);//RowID is the actual ID of the grid row and not the DB row 
    grid.invalidate(); 
    grid.render(); 
} 

我猜你已經知道如何處理PHP Ajax文件來加載數據,所以只需修改相同的文件來處理INSERT/DELETE/UPDATE和List ...我所有的動作函數都返回JSON,包括我的網格數據。快速瀏覽一下我的AJAX PHP文件將是:

<?php 
switch($_GET['action']) { 
    case 'delete': deleteItem($_POST['id']); 
        break; 
    case 'list': populateList(); 
        break; 
    case 'update': updateData(); 
        break; 
    default:  break; 
} 

/** Delete an item from the list/DB 
* @param int $id: id number of the item 
*/ 
function deleteItem($id) { 
    try{ 
     // Make the MySQL connection and save it into a global variable 
     $mysql = new mysqlDB(); 
     $mysql->connect(); 

     // Pull the computer name of the Combo Computer (if exist) 
     $sqlDel = sprintf("DELETE FROM table WHERE id='%s'", $id); 
     $resultDel = $mysql->query($sqlDel); 

     // close the MySQL connection 
     $mysql->disconnect(); 

     print '{ "affected_rows" : '.$resultDel.', "error_msg" : "" }'; 
    }catch(Error $e){ 
     print '{ "affected_rows" : 0, "error_msg" : "'.$e->getErrorString().'" }'; 
    } 
} 

/** Populate the list with data */ 
function populateList() { 
    try{ 
     // Make the MySQL connection and save it into a global variable 
     $mysql = new productionDB(); 
     $mysql->connect(); 
     $mysqli = $mysql->getMysqliObj(); 
     $mysqli->set_charset("utf8"); 

     $sqlTable = "SELECT id, title FROM table"; 
     $result = $mysql->query($sqlTable); 

     while($row = $result->fetch_object()) { 
      $tabData[] = array("id" => $row->id, 
           "title" => $row->title 
          ); 
      $nbRows = $result->num_rows; // how many rows does the table have in total? 
     } 

     // close the MySQL connection 
     $mysql->disconnect(); 

     // Fill the JSON String with the BOM Header info 
     $jsonStr .= '{"data":'.json_encode($tabData).',"info" : { "rows" : "'.$nbRows.'"}}'; 

     print $jsonStr; 
    }catch(Error $e){ 
     print '{ "affected_rows" : 0, "error_msg" : "'.$e->getErrorString().'" }'; 
    } 
} 


/** Update some data on the DB */ 
function updateData() { 
    try{ 
     // Make the MySQL connection and save it into a global variable 
     $mysql = new productionDB(); 
     $mysql->connect(); 
     $mysqli = $mysql->getMysqliObj(); 
     $mysqli->set_charset("utf8"); 

     $groups = ''; 
     $groupSet = $_POST['defect_group']; 
     if(isset($groupSet)) { 
      if(is_array($groupSet)) { 
       foreach($groupSet AS $group) { 
        $groups .= $group.","; 
       } 
       $groups = substr($groups, 0, -1); // remove last unused comma "," 
      } 
      else { 
       $groups = $groupSet; 
      } 
     } 

     // then make the UPDATE on the table 
     $sqlUpdate = sprintf('UPDATE title="%s", WHERE id=%d', 
          $mysqli->real_escape_string($_POST['title']) 
          $_POST['id'] 
          ); 
     $result = $mysql->query($sqlUpdate); 

     // close the MySQL connection 
     $mysql->disconnect(); 

     print '{ "affected_rows" : '.$result.', "error_msg" : "" }'; 
    }catch(Error $e){ 
     print '{ "affected_rows" : 0, "error_msg" : "'.$e->getErrorString().'" }'; 
    } 
} 

這應該是足以讓你在路上...享受:)

+0

實際上我加載的數據格式不是數據,不是json。因此,如果你分享完整的代碼,你會介意嗎?yup,im not good @ javascript。 – Bari 2013-03-22 06:43:37

+0

我添加了PHP的其餘部分,希望你對此有足夠的瞭解,因爲現在已經很完整了......如果你需要更多在javascript的幫助下,你應該看一下slickgrid的示例代碼。以數組形式加載數據並不遙遠,只需使用JSON對其進行編碼,然後就可以了...請參閱我的PHP示例 – ghiscoding 2013-03-22 20:06:30

+0

no feedback .. 。很高興知道它是否有效... – ghiscoding 2013-03-27 02:28:38