2017-06-05 95 views
0

如何使用Ajax回調jquery的數據表,即通話功能上的點擊?:如何使用jQuery的數據表與Ajax調用

這個作品

$(document).ready(function() { 
    var table = $('#example').DataTable(); 

    $('#example tbody').on('click', 'tr', function() { 
     var data = table.row(this).data(); 
     alert('You clicked on '+data[0]+'\'s row'); 
    }); 
}); 

與Ajax調用替換alert('You clicked on '+data[0]+'\'s row');

不工作

$(document).ready(function() { 
    var table = $('#example').DataTable(); 

    $('#example tbody').on('click', 'tr', function() { 
     var data = table.row(this).data(); 
     //alert('You clicked on '+data[0]+'\'s row'); 

     $.ajax({ 
       url: '/process', 
       data: data[0], 
       type: 'POST', 
       success: function(response) { 
        $("#response_placeholder").html(response); 
       }, 
       error: function(error) { 
        console.log(error); 
       } 
     }); 

    }); 
}); 

後端

#--app.py---- 

@app.route('/process', methods=['POST']) 
def process_data(): 
    data = request.form['data[0]']; 
    print data 
    return render_template('mypage.html', result=data) 

回答

1

嘗試使用此。

$('body').delegate('#example tbody tr','click' , function() { 


}); 

委託可以幫助添加事件添加到dom被加載後的元素。

也實在是很方便的將數據放在一個對象像這樣

data: {data: data[0]}, 

和網址應包含一個擴展可能

url: '/process.js', // or process.php depends on what extension it has. 

和標準應定義3個屬性即會返回錯誤,例如。

error: function(jqXHR, textStatus, errorThrown) {