Create new row with nested tables with Ajax reques

2019-07-08 08:57发布

问题:

I'm trying to create a similar functionality to this one: http://www.datatables.net/release-datatables/examples/api/row_details.html.

The only major difference to my code is that I'm trying to get the data through Ajax, and it does not work!

The Ajax request itself is made successfuly and I can see the HTML code inside the response.

My JS Code:

/* Creata TableData
--------------------------------------------*/
function fnFormatDetails ( StreetVal, oTable, nTr )
{
    var sOut = $.ajax({
      url: "ajax.php",
      data: StreetVal,
      success: function(data) {

          console.log(data);
          return data;

      }
    });

    return sOut;
}

$(document).ready( function(){


    $('.table-data tbody tr td a').addClass('closed');

    var oTable = $('.table-data').dataTable({ 
        "sPaginationType": "full_numbers", 
        "bStateSave": false, 
        "bRetrieve": true
    });

    $('.table-data tbody tr td a').live('click', function (event) {

        var StreetVal = $(this).attr('href').split('#')[1];
        var nTr = this.parentNode.parentNode;

        if( $(this).hasClass('closed') ) {

            $(this).removeClass('closed').addClass('open').html(' - ');
            oTable.fnOpen( nTr, fnFormatDetails( StreetVal, oTable, nTr ), 'details' );

        } else {

            $(this).removeClass('open').addClass('closed').html(' + ');
            oTable.fnClose( nTr );
        }

        return false;


    });

});

The problem is that it is throwing an error:

Could not convert JavaScript argument arg 0 [nsIDOMHTMLTableCellElement.appendChild] [Break On This Error] nNewCell.appendChild( mHtml );

at line 1776 of jquery.dataTables.js / v. 1.8.3.dev

What is the problem? Any suggestion much appreciated.

回答1:

Actually returning "sOut.responseText" instead of sOut in fnFormatDetails seems to work.



回答2:

It looks like nTr is a JS node, not a Jquery element. You could try setting nTr like this:

var nTr = $(this).parent("tr")[0];

Also, try putting "async: false" in the Ajax request to make sure its' completed before calling the function.



回答3:

Working JS code:

function fnFormatDetails ( StreetVal, oTable, nTr )
{
    var sOut = $.ajax({
      url: "ajax.php",
      async: false, // added 
      data: StreetVal,
      success: function(data) {
          return data;            
      }
    });

    return sOut.responseText; / changed form `return sOut`
}