php - 在 ajax 查询中使用动态变量

标签 php jquery ajax variables get

我正在努力将 GET 变量传递到 jquery 文件中。

我的代码是

function upload(files){ // upload function
        var fd = new FormData(); // Create a FormData object
        for (var i = 0; i < files.length; i++) { // Loop all files
            fd.append('file_' + i, files[i]); // Create an append() method, one for each file dropped
        }
        fd.append('nbr_files', i); // The last append is the number of files

        $.ajax({ // JQuery Ajax
            type: 'POST',
            url: 'ajax/tuto-dd-upload-image.php?order=5', // URL to the PHP file which will insert new value in the database
            data: fd, // We send the data string
            processData: false,
            contentType: false,
            success: function(data) {
                $('#result').html(data); // Display images thumbnail as result
                $('#dock').attr('class', 'dock'); // #dock div with the "dock" class
                $('.progress-bar').attr('style', 'width: 100%').attr('aria-valuenow', '100').text('100%'); // Progress bar at 100% when finish
            },
            xhrFields: { //
                onprogress: function (e) {
                    if (e.lengthComputable) {
                        var pourc = e.loaded / e.total * 100;
                        $('.progress-bar').attr('style', 'width: ' + pourc + '%').attr('aria-valuenow', pourc).text(pourc + '%');
                    }
                }
            },
        });

我需要 url: 'ajax/tuto-dd-upload-image.php?order=5' 中的 5 作为通过 url 传递的可变 order例如 domain.com/?order=XX

最佳答案

您可以使用 PHP 并导出变量:

var orderId = <?php echo json_encode($_GET['order']); ?>;

function upload(files) {
    ...
    url: 'ajax/tuto-dd-upload-image.php?order=' + orderId,

或者你可以直接在javascript中解析它:

var orderId = self.location.search.match(/order=(\d+)/)[1];

// Then continue like the previous example

当然,如果 GET 参数有可能丢失,您可能需要对此进行一些错误检查。

关于php - 在 ajax 查询中使用动态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39919590/

相关文章:

php - 按小时对时间值进行分组

php - 连接被拒绝 [tcp ://IP-ADDRESS-HERE:6379] Redis. Laravel

javascript - 如何使用 .each 遍历 div 中的元素?

javascript - 什么是最简单、最著名、最老练的 AJAX 框架?

PHP: session 的替代品

php - 如何在 foreach 循环/if 语句中保留变量值

javascript - 如何在 Javascript 中暂停事件?

javascript - 在 Bootstrap 模态中滚动到 DIV

javascript - ajax POST 处理程序循环

javascript - php mysql数据表在同一页面保存和编辑