【问题标题】:Dynamically load data from server to "select" type input fields in datatables从服务器动态加载数据到数据表中的“选择”类型输入字段
【发布时间】:2014-01-03 09:09:06
【问题描述】:

我有一个由函数加载器调用的 PHP 代码,该代码仅在数据表中的 onInitCreate 事件上触发。我想要做的是,当用户点击add button 时,它必须在select 字段中加载教师姓名。

我已经尝试过这段代码,但它什么也没返回,或者我应该说一个空值。我相信它应该正好返回一行。 这是我的 PHP 代码,用于获取教师名称并返回它。

getFacultyNames.php

<?php
error_reporting(-1);
require_once("config.php"); 


$sql="SELECT lastName, firstName, middleName FROM table_faculty";
$result = mysql_query($sql);
$stack=array();

if($result === FALSE) {
    die(mysql_error()); // TODO: better error handling
}

    while($row = mysql_fetch_array($result))
          {
            $name = $row[0]." ,".$row[1]." ".$row[2];
            array_push($stack,array("label" => $name, "value" => $name));
          }
echo json_encode($stack); //here it returns [{"label":"Last ,First Middle","value":"Last ,First Middle"}]
?>

jquery代码:

function loader(){
$.ajax({
  "url": 'php/getFacultyNames.php',
  "async": false,
  "dataType": 'json',
  "success": function (json) {

         console.log( json );
         //the getFacultyNames.php is now returning correct values, 
         //but how would I be able to get the value of the json code properly?
         //it always throws an error ""parsererror" SyntaxError
         //is it proper to have a code `return json;` in this success function?
    },
    "error" : function( jqXHR, textStatus, errorThrown ){ console.log( jqXHR, textStatus, errorThrown ); }

});
}

这是我的编辑器初始化代码:

var editor = new $.fn.dataTable.Editor( {
        "ajaxUrl": "php/table.facultyloading.php",
        "domTable": "#facultyloading",
        "events": {
            "onInitCreate":function (){
                editor.add( {
                    "label": "Assign to Faculty",
                    "name": "facultyName",
                    "type": "select",
                    "ipOpts":loader()      // Returns array of objects - .ajax() with async: false
                    });
                }
            },
        "fields": [
            {
                "label": "Subject Name",
                "name": "name",
                "type": "select",
                "ipOpts": [
                    {
                        "label": "sample",
                        "value": "sample"
                    }
                ]
            },
            {
                "label": "Day",
                "name": "day",
                "default": "Monday",
                "type": "checkbox",
                "ipOpts": [
                    {
                        "label": "Monday ",
                        "value": "Monday "
                    },
                    {
                        "label": " Tuesday ",
                        "value": " Tuesday "
                    },
                    {
                        "label": " Wednesday ",
                        "value": " Wednesday "
                    },
                    {
                        "label": " Thursday ",
                        "value": " Thursday "
                    },
                    {
                        "label": " Friday ",
                        "value": " Friday "
                    },
                    {
                        "label": " Saturday",
                        "value": " Saturday"
                    }
                ],
                "separator": "|"
            },
            {
                "label": "Start Time",
                "name": "startTime",
                "type": "text"
            },
            {
                "label": "End Time",
                "name": "endTime",
                "type": "text"
            },
            {
                "label": "Room",
                "name": "room",
                "type": "text"
            }
        ]
    } );  

我似乎无法弄清楚出了什么问题。我错过了什么吗?你能帮帮我吗?
提前致谢!

【问题讨论】:

  • 警告: mysql_ 函数自 PHP 5.5.0 起已弃用,并将在未来删除。相反,应该使用 MySQLiPDO_MySQL 扩展名。
  • @bansi 谢谢。我稍后会修改它,但你认为这是它不起作用或没有返回任何值的原因吗?
  • 不是原因,只是中肯的建议
  • @bansi,我很难确定 OP 到底在哪里写“我正在使用 PHP 5.5.0 或更高版本”...
  • @Harvey 可能发生了错误,将以下选项添加到您的$.ajax 函数"error" : function( jqXHR, textStatus, errorThrown ){ console.log( jqXHR, textStatus, errorThrown ); } 以测试错误。

标签: php ajax jquery datatables jquery-datatables


【解决方案1】:

我已经将 mysql 函数转换为 PDO_MySQL,最后它可以工作了,这是我的新 getFacultyNames.php,我还稍微修改了我的 jquery 代码。感谢你的帮助! :)

getFacultyNames.php

<?php
error_reporting(-1);
require_once("config.php"); 
$stack=array();

$stmt = $dbh->prepare("SELECT lastName, firstName, middleName FROM table_faculty");
if ($stmt->execute()) {
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $name = $row['lastName']." ,".$row['firstName']." ".$row['middleName'];
    array_push($stack,array($name,$name));
  }

  echo json_encode($stack);
}
?>

jquery 代码

function names(){       
    var test= new Array({"label" : "a", "value" : "a"});
    test.splice(0,1);
        $.ajax({
          "url": 'php/getFacultyNames.php',
          "async": false,
          "dataType": 'json',
          "success": function (json) {
              for(var a=0;a < json.length;a++){
                obj= { "label" : json[a][0], "value" : json[a][1]};
                test.push(obj);
              }
            },
          "error" : function( jqXHR, textStatus, errorThrown ){ console.log( jqXHR, textStatus, errorThrown ); }

        });
        return test;
    }

【讨论】:

    【解决方案2】:

    die 添加到getFacultyNames.php 的末尾。

     echo json_encode($stack);
     die;
    

    更新 尝试删除"dataType": 'json'并在callbaks中设置:

       try {
         json = JSON.parse(data);
       }
       catch (e) {
         console.log("Parse error:"+e);
       };
    

    【讨论】:

    • 我添加了 die 但我得到了同样的错误。 "parsererror" SyntaxError.
    • @Harvey 在控制台响应中看到(服务器返回什么)。getFacultyNames.php 中的问题。
    • 我已经在success函数中插入了上面的代码,删除"dataType": 'json'并运行它。在控制台中显示Parse error:ReferenceError: data is not defined
    【解决方案3】:

    使用这个

    function loader(){
      var responseText = $.ajax({
        "url": 'php/getFacultyNames.php',
        "async": false,
        "dataType": null,
        "error" : function( jqXHR, textStatus, errorThrown ){ 
                 console.log( jqXHR, textStatus, errorThrown ); 
         }
       }).responseText;
    
      return $.parseJSON(responseText)
    }
    

    这将执行 AJAX 调用并返回正确格式的 JSON 对象。

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 2018-06-07
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      相关资源
      最近更新 更多