在Kendo UI中添加记录功能总是插入两行

时间:2016-07-21 07:24:04

标签: javascript php mysql kendo-grid

非常感谢您一如既往的支持。我在使用Kendo UI for PHP时遇到了一个大问题。 我正在使用这个javascript代码用于Kendo UI网格:

<script>
$(document).ready(function () {  
var suffers = [];
var solvers = [];
var actions = [];

var dataSource = new kendo.data.DataSource({
pageSize: 30,
//data: products,
 transport: {
              //read: "data/fActions.php",
                                        read: "data/fetchActions.php",
                                        update: {url:"data/updateC.php", type:"POST",complete: function (e) {
                                            //alert ("completado");
                                            grid.dataSource.read(); 
                                            grid.refresh();
                                            }},
                                        create: {url:"data/createC.php",type:"POST", complete: function (e) {
                                            //alert ("completado");
                                            grid.dataSource.read(); 
                                            grid.refresh();
                                            }},
                                        destroy: {url:"data/destroyC.php",type:"POST", complete: function (e) {
                                            //alert ("completado");
                                            grid.dataSource.read(); 
                                            grid.refresh();
                                            }}
                                        /*parameterMap: function(options, operation)
                                        {
                                            if (operation == "create" & options.models)
                                            {
                                                return JSON.stringify({ "action": options.models});
                                            }
                                        }*/
                        },
autoSync: true,
batch: true,    
schema: {
  model: {
    id: "ActionID",
    fields: {
    ActionID: { editable: false, type: "number"},
      DateCreated: { field: "DateCreated", editable:"inline", defaultValue: Date()  },
      SufferID: {field: "SufferID" , editable:"inline", defaultValue: 1 },
      Problem: { validation: { required: true }, editable:"inline", defaultValue: "Write here the problem"  },
      SolverID: { field: "SolverID" , editable:"inline", defaultValue: 1   },
      DateSolved: { field: "DateSolved" , editable:"inline", defaultValue: Date() },
      ActionStatus: { field: "ActionStatus", defaultValue: 0, editable:"inline" }

    }
  }
}
});
var onDataBound = function() {
$('td').each(function(){if($(this).text()=='Closed')
{$(this).addClass('red')}});
$('td').each(function(){if($(this).text()=='Open')   
{$(this).addClass('green')}});

};
var grid = $("#Skpi1div").kendoGrid({
dataSource: dataSource,
dataBound: onDataBound,
filterable: true,
scrollable: false,
toolbar: ["create"],
autoBind: false, // disable autobinding as we should wait for the categories to be loaded
columns: [
    { field:"ActionID",title:"ID", width: "65px" },
    { field:"DateCreated", title:"Date", format:"{0:yyyy-MM-dd}", editor: dateCreatedEditor, template: "#=getDateCreated(DateCreated)#", type:"date", width: "100px"},

    { 
    field: "SufferID", width: "120px",
    editor: sufferDropDownEditor,
    title: "Created By",
    template: "#=getSufferName(SufferID)#"
  },
  { field:"Problem",title:"Problem / Cause" },
     { 
    field: "SolverID", width: "140px",
    editor: solverDropDownEditor,
    title: "Solved By",
    template: "#=getSolverName(SolverID)#"
  },   

 { field:"DateSolved", title:"Date Solved", format:"{0:yyyy-MM-dd}", editor: dateSolvedEditor, template: "#=getDateSolved(DateSolved)#", type:"date", width: "90px"},
  { 
    field: "ActionStatus", width: "90px",
    editor: actionDropDownEditor,
    title: "Status",
    template: "#=getActionName(ActionStatus)#",
    attributes: {
        "class": "actions"
    }
  },

     { command: [{text:"Delete record",name:"destroy"}], title: " ", width: "200px" }
  ],
editable: true ,
}).data("kendoGrid");

$.getJSON("actionsDEPARTMENT.php", function(data) {
  suffers = data;
  dataSource.fetch();
});
$.getJSON("actionsDEPARTMENTsolvers.php", function(data) {
  solvers = data;
  dataSource.fetch();
});
$.getJSON("actionsEX.php", function(data) {
  actions = data;
  dataSource.fetch();
});
});

function sufferDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({      
  dataTextField: "SufferName", 
  dataValueField: "SufferID",
  dataSource: suffers,
  change: function(e) {
    //  this.css ("background-color", "blue");
 //  var value = this.value();
//  alert (value);
// Use the value of the widget
} 
});
}


function getSufferName(SufferID) {
//alert ("suffer:" + SufferID);
  for (var idx = 0, length = suffers.length; idx < length; idx++) {
  if (suffers[idx].SufferID == SufferID) {

    return suffers[idx].SufferName;
  }
}
}

function solverDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({      
  dataTextField: "SolverName", 
  dataValueField: "SolverID",
  dataSource: solvers,
  change: function(e) {
    //  this.css ("background-color", "blue");
 //  var value = this.value();
//  alert (value);
// Use the value of the widget
} 
});
}


function getSolverName(SolverID) {
//alert (SolverID);
for (var idx = 0, length = solvers.length; idx < length; idx++) {
  if (solvers[idx].SolverID == SolverID) {

    return solvers[idx].SolverName;
  }
}
}
function actionDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({      
  dataTextField: "ActionName",
  dataValueField: "ActionStatus",
  dataSource: actions,
  change: function(e) {
 $('td').each(function(){if($(this).text()=='Closed')      
{$(this).addClass('red')}});
    $('td').each(function(){if($(this).text()=='Open')    
{$(this).addClass('green')}});
} 
});
}

function getActionName(ActionStatus) {
for (var idx = 0, length = actions.length; idx < length; idx++) {
  if (actions[idx].ActionStatus == ActionStatus) {

    return actions[idx].ActionName;
  }
}
}

function getDateCreated(DateCreated) {
var dateCreated = kendo.toString(DateCreated, "yyyy/MM/dd");
//alert (dateCreated);
  return  dateCreated;
}

function getDateSolved(DateSolved) {
var dateSolved = kendo.toString(DateSolved, "yyyy/MM/dd");
//alert (dateCreated);
return  dateSolved;
}

function dateSolvedEditor(container, options) {
$('<input data-text-field="' + options.field + '" data-value-field="' +  options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
        .appendTo(container)
        .kendoDatePicker({});
}
function dateCreatedEditor(container, options) {
$('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
        .appendTo(container)
        .kendoDatePicker({});
}
</script>

创建和删除php文件的代码如下:

//CREATE.php
<?php
header("Content-type: application/json");
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die('Could not connect: ' . mysql_error());
} else {
mysql_select_db("mapdata", $con);
if (strlen ($_POST['models'][0]['DateCreated'])> 12 )
{   
 list($diaChar, $mes, $dia, $year) = explode(' ', $_POST['models'][0]['DateCreated']);
 $fecha = DateTime::createFromFormat('j-M-Y', $dia . "-" . $mes . "-" . $year);
 $dateCreated =  $fecha->format('Y-m-d');
}
else
{
     $dateCreated = $_POST['models'][0]['DateCreated'];
}
echo $dateCreated;

if (strlen ($_POST['models'][0]['DateSolved'])> 12 )
{   
 list($diaCharS, $mesS, $diaS, $yearS) = explode(' ', $_POST['models'][0]['DateSolved']);
 $fechaS = DateTime::createFromFormat('j-M-Y', $diaS . "-" . $mesS . "-" . $yearS);
 $dateSolved =  $fechaS->format('Y-m-d');
}
else
{
     $dateSolved = $_POST['models'][0]['DateSolved'];
}

 echo ($dateSolved);
$modalidad = mysql_query ("SELECT MAX(`ActionID`) FROM actionsc", $con);
$idCurrent = (mysql_result ($modalidad, 0));
$idCurrent = $idCurrent + 1;
echo $idCurrent;

$rs = mysql_query("INSERT INTO actionsc (ActionID, DateCreated, SufferID, Problem, SolverID, DateSolved, ActionStatus) VALUES('". mysql_real_escape_string($idCurrent, $con) . "','". mysql_real_escape_string($dateCreated, $con) . "', '" . mysql_real_escape_string($_POST['models'][0]['SufferID'], $con) . "', '" . mysql_real_escape_string($_POST['models'][0]['Problem'], $con) . "', '" . mysql_real_escape_string($_POST['models'][0]['SolverID'], $con) . "', '" . mysql_real_escape_string($dateSolved, $con) . "', '" .     mysql_real_escape_string($_POST['models'][0]['ActionStatus'], $con) . "')");


if ($rs) {
echo json_encode($rs);
$res = mysql_query("SELECT * From actionsc WHERE `ActionID`='$idCurrent'");

$arr = array();
while($obj = mysql_fetch_array($res))
{
  $arr[] = array(
     'ActionID' => $obj["ActionID"],
    'DateCreated' => $obj["DateCreated"],
     'SufferID' => str_replace("\'", "'", $obj["SufferID"]),
     'Problem' => str_replace("\'", "'", $obj["Problem"]),
     'SolverID' => str_replace("\'", "'", $obj["SolverID"]),
     'DateSolved' => str_replace("\'", "'", $obj["DateSolved"]),
     'ActionStatus' => str_replace("\'", "'", $obj["ActionStatus"]),
  ); 
echo json_encode($arr);

}
}
else {
    header("HTTP/1.1 500 Internal Server Error");
     echo "Failed on insert:";
}
mysql_close($con);
}
?> 

//DESTROY
<?php
header("Content-type: application/json");
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
  die('Could not connect: ' . mysql_error());
} else {
   mysql_select_db("mapdata", $con);
   echo ( $_POST['models'][0]['ActionID']);
   $rs = mysql_query("DELETE FROM actionsc WHERE ActionID = " . $_POST['models'][0]['ActionID']);
   if ($rs) {
    echo json_encode($rs);
  }
  else {
        header("HTTP/1.1 500 Internal Server Error");
        echo "Failed on delete: " . $_POST['models'][0]['ActionID'];
  }
   mysql_close($con);
}
?> 

当我尝试添加新记录时以及当我尝试删除现有记录时出现问题:

  • 当CREATE时,createC.php的网络命令GET出现两次,并且向dataSource添加了两条记录。我几天在论坛上一直在阅读如何解决这个问题。

我尝试了两件事: 1)当create完成后,我试图读取并刷新我的dataSource 2)在json中手动返回最近添加的记录。

结论:问题仍然存在。

  • 当DESTROY时,发布的记录的ID(ActionID)始终相同。不知道这个。

我已经度过了最后四天,对不起我的代码。 非常感谢你的支持,非常感谢你。

问候,马努。

1 个答案:

答案 0 :(得分:0)

如果您的--with-opus=[absolute-path-to]/opus-dev-lib操作正在执行两次,则可能表示您的Javascript正在加载两次。