如何在ajax中将数据传递给JSON使用if else条件

时间:2016-04-07 20:10:08

标签: php json ajax

我使用jQuery Datatable在PHP中显示来自数据库的数据。我将数据存储在role_type中值为0和1的数据库中。我想显示值为0的Admin和值为1的Employee。

通过AJAX发布的数据显示在下表中:

<table id="employee_grid" class="display" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>User Name</th>
            <th>Employee code</th>
            <th>Password</th>
            <th>Created date</th>
            <th>Role</th>
            <th>Action</th>
        </tr>
    </thead>
</table>

我的Ajax请求数据是:

<script type="text/javascript">
$( document ).ready(function() {

$('#employee_grid').DataTable({
                 "bProcessing": true,
         "serverSide": true,
         "ajax":{
            url :"response_user.php", // json datasource
            type: "post",  // type of method  , by default would be get
            "aoColumnDefs" : [
                 {
                   'bSortable' : false,
                   'aTargets' : [3,4]
                 }],
            "dataSrc": function (jsonData) {
              for ( var i=0, len=jsonData.data.length ; i<len ; i++ ) {

        jsonData.data[i][0] = i+1;
        // use if conditation to display Admin for value 0 and Employee for value 1 but its not working
        jsonData.data[i][6] = if (jsonData.data[i][6]!=1) {+'<a href="Admin.php" class="btn btn-warning">Admin</a>'+}else{+'<a href="Employee.php" class="btn btn-success">Employee</a>'+};
        jsonData.data[i][7] = '<a class="btn btn-danger" href="delete.php?id='+jsonData.data[i][0]+'" class="btn btn-primary btn-xs">Delete</a>';
              }

              return jsonData.data;
            },
            error: function(){  // error handling code
              $(".employee-grid-error").html("");
              $("#employee_grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found.</th></tr></tbody>');
              $("#employee_grid_processing").css("display","none");
            }
          }
        });   
});
</script>

1 个答案:

答案 0 :(得分:0)

我使用三元运算符:

jsonData.data[i][6] += jsonData.data[i][6]!=1 ? '<a href="Admin.php" class="btn btn-warning">Admin</a>' : '<a href="Employee.php" class="btn btn-success">Employee</a>';

或者你可以将逻辑放在别处:

var content;
if (jsonData.data[i][6]!=1) {
  content = '<a href="Admin.php" class="btn btn-warning">Admin</a>';
} else {
  content = '<a href="Employee.php" class="btn btn-success">Employee</a>';
}
jsonData.data[i][6] += content;

无论你认为哪个更具可读性。

相关问题