通过Ajax在URL中传递变量

时间:2015-06-24 15:36:00

标签: javascript php datatables

这是一段使用jQuery Datatables的JavaScript代码。

我想通过Ajax在URL中传递变量ident(在下面的示例中等于2,见下文:

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

传不通。但是,将'+ ident +'替换为2有效。

那条线有什么问题?

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 }
            ]
        }
    } );
} );

2 个答案:

答案 0 :(得分:1)

您的字符串连接中有错误。 替换此行:

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

有了这个:

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

答案 1 :(得分:1)

您正在错误地构建网址。

替换:

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

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

如果ident不仅包含数字,您还需要使用encodeURIComponent()将其编码为encodeURIComponent(ident),以正确转义特殊字符。