2015-06-24 177 views
0

這是一段使用jQuery Datatables的JavaScript代碼。通過Ajax在URL中傳遞變量

我想通過變量ident(它等於2在下面的例子中)在通過Ajax的URL,見下圖:

ajax: "staff2.php?userid='+ ident +'" 

它不是通過正常。但是用2替代'+ ident +'的作品。

那麼這條線有什麼問題?

var ident = '2'; 


var editor; // use a global for the submit and return data rendering in the examples 
$(document).ready(function() { 
    editor = new $.fn.dataTable.Editor({ 
     ajax: "staff2.php?userid='+ ident +'", 
     table: "#building", 
     "bProcessing": true, 
     "bServerSide": true, 
     fields: [ { 
       label: "", 
       name: "building" 
      } 
     ] 
    }); 
    // Activate an inline edit on click of a table cell 
$('#building').on('click', 'tbody td', function() { 
    editor.inline(this); 
}); 
    $('#building').DataTable({ 
     //dom: "Tfrtip", 
     "searching": false, 
     "bInfo" : false, 
     "bPaginate": false, 
     "bSort": false, 
     "bVisible": false, 
     ajax: "staff2.php?userid='+ ident +'", 
     columns: [ 
      { data: null, defaultContent: '', orderable: false }, 
      { data: "building" },   
     ], 
     order: [ 1, 'asc' ], 
     tableTools: { 
      sRowSelect: "os", 
      sRowSelector: 'td:first-child', 
      aButtons: [ 
       { sExtends: "editor_create", editor: editor }, 
       { sExtends: "editor_edit", editor: editor }, 
       { sExtends: "editor_remove", editor: editor } 
      ] 
     } 
    }); 
}); 

回答

1

你沒有正確地構建URL。

替換:

ajax: "staff2.php?userid='+ ident +'", 

ajax: "staff2.php?userid=" + ident, 

如果ident不僅包含數字,還需要與encodeURIComponent()編碼作爲encodeURIComponent(ident)正確轉義特殊字符。

+0

完美 - 謝謝 – Alex

1

在字符串連接中出現錯誤。 替換此行:

ajax: "staff2.php?userid='+ ident +'", 

有了這個:

ajax: "staff2.php?userid=" + ident, 
+0

如果'ident'等於'2',你的代碼會生成URL'staff2.php?userid ='2'',這是不正確的。 –

+0

感謝您發現@Gyrocode。代碼相應調整。 – NaijaProgrammer