javascript - Kendo UI 中添加记录功能,始终插入两行

标签 javascript php mysql kendo-grid

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

<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)创建完成后,我尝试读取并刷新我的数据源 2)手动以json形式返回最近添加的记录。

结论:问题仍然出现。

  • 当 DESTROY 时,发布的记录的 ID (ActionID) 始终相同。对此一无所知。

过去四天我都在这度过,对我的代码感到抱歉。 非常感谢您的支持,真的非常感谢。

问候,马努。

最佳答案

如果您的 CRUD 操作执行了两次,则可能表明您的 Javascript 被加载了两次。

关于javascript - Kendo UI 中添加记录功能,始终插入两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38497622/

相关文章:

php - 在 php 站点上模拟(强)加载的程序

PHP 解析错误 : syntax error, CodeIgniter View 中的文件意外结束

php - 卡在一个简单的代码上

php - 如果id在数组中,vuejs检查复选框

php - 仅当我使用 PHP 登录时才能访问该页面

javascript - 在力图d3 js上添加标签

javascript - 加载列表(带图像)时添加回调函数

javascript - 如何捕获div内容并在模态框中显示?

javascript - 单击时甚至不会在我的 android 设备上触发

MySQL if 语句使用聚合函数返回错误结果