我有一段Javascript,它将用户选择的信息转发到外部PHP文件,并返回信息。在下面的代码中,您可以看到它通过POST将{'report':report}发送到该文件。那很好。
实际上,我需要添加另一个要发送的变量。它被称为“id”,但它在另一个函数中。有没有办法使该变量成为全局变量,然后合并它,以便将其发送到我的代码片段中(何时清除全局变量?)我也可以通过'url'属性发送它,并在我的PHP中使用GET…只是不知道如何实现。

$('#adminSelectReport a').live("click", function () {
    //Get id from clicked link:
    var report = $(this).attr('id');

    $.ajax({
        type: 'POST',
        url: 'getReportInfo.php',
        data: {
            'report': report
        },
        success: function (msg) {
            //everything echoed in your PHP-File will be in the 'msg' variable:
            $('#adminReportInfo').html(msg);
            $('#adminReportInfo').fadeIn(400);
        }
    });
});

更新:这是另一个将“id”发送到另一个页面的片段,用于获取信息。但是,我需要保留这个ID,并在我的原始代码上使用它。
$('#adminSelectCompany a').click(function() {
    //Get id from clicked link:
    var id = $(this).attr('id');

    $.ajax({
        type: 'POST',
        url: 'getReports.php',
        data: {'id': id},
        success: function(msg){
            //everything echoed in your PHP-File will be in the 'msg' variable:
            $('#adminSelectReport').html(msg);
            $('#adminSelectReport').fadeIn(400);
           $('#adminReportInfo').fadeOut(300);

        }
});
    });

最佳答案

所以听起来他们是通过一个链接选择一家公司,然后通过另一个链接选择一份报告,你需要记住选择了哪家公司。
为了避免全局变量,我可能只需向选定的公司链接添加一个类,然后按选定的类获取该元素,并获取其ID。如果需要,也可以使用该类进行样式设置。

var companies = $('#adminSelectCompany a');

companies.click(function () {

      // remove class from previously selected, and add to new one
    companies.filter('.selected').removeClass('selected');
    $(this).addClass('selected');

    $.ajax({
        type: 'POST',
        url: 'getReports.php',
        data: {
            'id': this.id
        },
        success: function (msg) {
            //everything echoed in your PHP-File will be in the 'msg' variable:
            $('#adminSelectReport').html(msg)
                                   .fadeIn(400);
            $('#adminReportInfo').fadeOut(300);

        }
    });
});

$('#adminSelectReport a').live("click", function () {

    $.ajax({
        type: 'POST',
        url: 'getReportInfo.php',
        data: {
            'report': this.id,
            'company': $('.selected')[0].id
        },
        success: function (msg) {
            //everything echoed in your PHP-File will be in the 'msg' variable:
            $('#adminReportInfo').html(msg);
            $('#adminReportInfo').fadeIn(400);
        }
    });
});

07-24 09:44
查看更多