0

我在解码 JSON 数据时遇到问题。实际上我希望将 slickgrid 的工作保存在 mysql 中。所以,我读了[问题]:使用 php 在 SlickGrid 中保存更改,但不知道如何解码数据。

这是我处理 JSON 的 PHP 脚本:

    <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.";
    }
    ?>

这是我试图解码的 JSON

...
<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>
4

1 回答 1

0

好的,这是我从 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().'" }';
    }
}

这应该足以让你上路......享受:)

于 2013-03-21T20:43:12.387 回答