jquery解码json
我对解码JSON数据有问题。实际上,我想把网格工作保存在mysql中。 所以,我读了[问题]:但不知道如何解码数据jquery解码json,jquery,json,slickgrid,Jquery,Json,Slickgrid,我对解码JSON数据有问题。实际上,我想把网格工作保存在mysql中。 所以,我读了[问题]:但不知道如何解码数据 下面是我处理JSON的PHP脚本: <script src="jquery-1.7.min.js"></script> <script type="text/javascript" src="jquery.json.js"></script> <?php if(isset($_POST['dat
下面是我处理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.";
}
?>
var obj=$.JSON.decode(输入[name='dataz'].val());
警报(“json解码:”+obj);
这是我试图解码的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>
。。。
$(函数(){
$(“表格”)。提交(
函数(){
$(“输入[name='dataz']”)val($.JSON.encode(数据));
}
);
});
好的,这是我插入、更新、删除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();
}
var ajaxFileURL=“fileAjax.php?action=list”;
函数populateList(ajaxFileURL){
var msgDelete='是否确实要删除该行?';
var deleteIcon=“”;
//在ID列上附加删除事件
变量列=[
{id:“id”,名称:“id”,字段:“id”,宽度:8,格式化程序:函数(r,c,id,def,datactx){return”“;},
{id:“title”,name:“title”,field:“title”,width:70,minWidth:50,cssClass:“cell title”,sortable:true,editor:Slick.Editors.Text}
];
变量选项={
enableCellNavigation:true,
可编辑:真
};
$.getJSON(ajaxFileURL,函数(ServerResponse){
var groupItemMetadataProvider=new Slick.Data.groupItemMetadataProvider();
dataView=新的Slick.Data.dataView({
groupItemMetadataProvider:groupItemMetadataProvider,
inlineFilters:真
});
grid=new Slick.grid(“#myGrid”、数据视图、列、选项);
//本节讨论插入/更新
grid.onCellChange.subscribe(函数(e,args){
//updateItem(args.item.id,args.item);
if(typeof(args.item.id)=“未定义”)
$.post(ajaxFileURL+“?action=insert”,args.item);
否则{
$.post(ajaxFileURL+“?操作=更新”,args.item,函数(ServerResponseUpt){
//如果数据库返回错误,则将其显示给用户并撤消单元格更改
if(parseInt(ServerResponseUpt.infected_行)<1 | | ServerResponseUpt.error_msg!=“”){
警报(“更新错误:+ServerResponseUpt.ERROR\u msg”);
args.item[previousCellNames[0]]=PreviousCellValue[0];
grid.updateRow(args.row);
grid.updateRowCount();
grid.render();
}
previousCellNames=新数组();
previousCellValues=新数组();
}“json”);
//刷新网格上的数据
grid.updateRow(args.row);
grid.updateRowCount();
grid.render();
}
});
//在连接所有事件后初始化模型
dataView.beginUpdate();
setItems(ServerResponse.data);
endUpdate();
}//美元.getJSON()的结尾
}//populateList()的结尾
//要删除的外部函数
函数removeClick(ajaxFileURL、dbRowId、gridRow){
$.post(ajaxFileURL+'?action=delete',{id:dbRowId});
var item=dataView.getItem(gridRow);//RowNum是行数
var rowID=item.id
dataView.deleteItem(rowID);//rowID是网格行的实际ID,而不是DB行
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().'" }';
}
}
如果只是关于如何解析JSON,这里已经给出了答案:。但是,这可能不是你唯一的问题。你必须专门使用JSON吗?因为我对MySQL的处理方式是使用事件grid.onCellChange.subscribe(函数(e,args){$.post…
不使用任何JSON,尽管我将JSON中的问题作为回调返回,顺便说一句,您可能没有任何表单提交的返回反馈。如果您需要进一步的帮助,我将发布“答案”@Ghicoding:你能分享代码吗?事实上,我加载的是数组格式的数据,而不是json。你介意分享完整的代码吗?是的,我不是很好的@javascript。我添加了PHP的其余部分,希望你已经足够了,因为这已经很完整了……如果你需要javascript方面的更多帮助,你应该看看slickgrid示例代码。将数据加载为数组并不遥远,只需用JSON对其进行编码,就可以了…看我的PHP示例实际上我正在努力让它工作,我告诉你我不擅长javascript。代码对我来说仍然很难阅读。也许我需要一个工作的演示。它在PHP上运行。我仍然在研究它。很好,最后我可以让它工作,但在插入和更新。是的,需要很长时间才能完成。但我仍然好奇如何删除?这是我的代码抱歉我的示例不完整,从头开始时有很多代码…我在顶部编辑了我的代码,您需要声明数据视图
对象(请参见$.getJSON
后面的我的代码,并绑定$末尾的数据。getJSON
将其添加到代码中,而不是像您那样循环。然后我还修改了removeClick()
函数,我使用的是多个网格,而您没有(我将grid1改为网格,不那么混乱)。