通过 Ajax 在 URL 中传递变量

Pass variable in URL via Ajax

这是一段使用 jQuery 数据表的 JavaScript 代码。

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

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

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

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

有了这个:

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

您构建的 URL 不正确。

替换:

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

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

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