【问题标题】:JavaScript file upload after 3G compression3G压缩后的JavaScript文件上传
【发布时间】:2026-02-20 12:15:01
【问题描述】:

我的网站chillingsafe.com/upload.php 上的一个页面有问题,我希望你们中的一些人能够帮助我。

许多 3G 网络提供商压缩网页和图像以减少使用的数据量,他们通过注入这行代码脚本 src="http://1.2.3.8/bmi-int-js/bmi.js 来做到这一点"language="javascript" 就在开始的 html 标记之后。

这样做的问题在于,它不仅会缩小图像,而且会压缩您的代码,并且通常会将其强制为一行。完成此操作后,我网站上的上传系统将无法正常工作。它实际上导致了我在 Chrome 控制台中发现的这个错误,Uncaught TypeError: Cannot read property 'innerHTML' of null。我明白这意味着什么,但我不知道如何解决,尤其是在标准宽带连接完全没有问题的情况下。

如果有人能在这方面帮助我,我将不胜感激。

谢谢, 乔

【问题讨论】:

  • 请包含上述代码,而不是“脚本”标签...
  • 脚本很长。
  • 它必须做更多的只是压缩(例如删除空格),否则它不会成为问题。顺便问一下,您使用哪些浏览器进行测试?旧版本的 IE,使用 innerHTML 时失败。
  • Chrome 和 Firefox 的最新版本。
  • 这是注入脚本对代码help.chillingsafe.com/download/file.php?id=1所做的截图

标签: javascript


【解决方案1】:

快速浏览了您的代码。 (内嵌/嵌入在主页中。)

这里有一些问题。

1.) 你几乎从不使用var。结果,您的所有变量都被提升到全局空间。

function foo() {
   answer = 42;
}
foo();

现在window.foo === 43,或者如果你愿意,直接foo

在您的一个作用域中,您还拥有use strict。结果,未定义的变量不会被提升,但您通常会得到:

Uncaught ReferenceError: somevariablename is not defined

2.) 你永远不会在 for in 循环中使用 hasOwnProperty()。始终使用:

for (x in y) {
    if (y.hasOwnProperty(x)) {
        ....
    }
}

如果是数组,请不要使用for in,但是:

var i;
for (i = 0 ; y.length ;  ++i) {

}

在您的代码中,您对数组做了很多 for in。不要!

3.) 在第 352 行,您缺少分号:

html += '" onClick="">' // ««« Missing semicolon!
if (isSuccess == false) {
html += data.error_result_html;

4.) 内联 cmets。

如果脚本被一些实施不佳的压缩器内联代码压缩是一个问题:

var x = 123;
// some comment
alert(x);

可能会导致

var x = 123; // some comment alert(x);

5.) 无法读取 null 的属性“innerHTML”

可能意味着您的某些代码被乱序执行。例如。它在 DOM 准备好之前执行。据我所知,只有最后一个间隔 thing 在 jQuery 的 ready 包装之外。尝试将其添加到包装器中。

$(document).ready(function () {

    ...

    function CheckTables() {
        $("table ").each(function (index) {
            $(this).find('tbody:empty').parent().hide();
            $(this).find('tbody:not(:empty)').parent().show();
        });
    }
    setInterval(CheckTables, 100);
});

您也可以尝试将 ready() 替换为:

$(window).load(function() {

});

在这两种情况下。


可能还有更多。先尝试修复数字 3。


从提取的代码中快速格式化和一些注释和变量插入等:


/* jshint sub:true, eqeqeq:false */
/* global $, ZeroClipboard, alert, bytesToSize, humanReadableTime */
/* exported updateTotalFilesText, setRowClasses, sendAdditionalOptions */
/* ============================================================================ */
var fileUrls = [];
var fileDeleteHashes = [];
var fileShortUrls = [];

var fileToEmail = '';
var filePassword = '';

var startTime = null;
var uploadComplete = false;
function getUrlsAsText() {
    var urlStr = '';
    for (var i = 0; i < fileUrls.length; i++) {
        urlStr += fileUrls[i] + "\n";
    }
    return urlStr;
}
function setupCopyAllLink() {
    $('#copyAllLink').attr('data-clipboard-text', getUrlsAsText());
    var clip = new ZeroClipboard(document.getElementById("copyAllLink"), {
        moviePath: "http://cdn.chillingsafe.com/scripts/zeroClipboard/ZeroClipboard.swf",
        text: getUrlsAsText()
    });
    clip.on('complete', function (client, args) {
        alert("" + args.text);
    });
}
function updateProgessText(progress, uploadedBytes, totalBytes) {
    var nowTime = (new Date()).getTime();
    var loadTime = (nowTime - startTime);
    if (loadTime === 0) {
        loadTime = 1;
    }
    var loadTimeInSec = loadTime / 1000;
    var bytesPerSec = uploadedBytes / loadTimeInSec;
    var textContent = '';
    textContent += '' + progress + '% complete';
    textContent += ' ';
    textContent += '(' + bytesToSize(uploadedBytes, 2) + ' of ' + bytesToSize(totalBytes, 2) + ')';
    $("#fileupload-progresstextLeft").html(textContent);
    var rightTextContent = '';
    rightTextContent += '' + humanReadableTime((totalBytes / bytesPerSec) - (uploadedBytes / bytesPerSec)) + ' remaining';
    rightTextContent += ' at ' + bytesToSize(bytesPerSec, 2) + 'P/s';
    $("#fileupload-progresstextRight").html(rightTextContent);
}
function updateTitleWithProgress(progress) {
    if (typeof (progress) == "undefined") {
        progress = 0;
    }
    if (progress === 0) {
        $(document).attr("title", "Upload - ChillingSafe");
    } else {
        $(document).attr("title", progress + "% complete - ChillingSafe");
    }
}
function getTotalRows() {
    var totalRows = $('#files .template-upload').length;
    if (typeof (totalRows) == "undefined") {
        return 0;
    }
    return totalRows;
}
function updateTotalFilesText(/*total*/) {
    //$('#uploadButton').html('upload '+total+' files');
}
function setRowClasses() {
    //$('#files tr').removeClass('even');
    //$('#files tr').removeClass('odd');
    //$('#files tr:even').addClass('odd');
    //$('#files tr:odd').addClass('even');
}
/* Never used
var lastEle = null;
function showAdditionalInformation(ele) {
    $('.sliderContent table').unbind();
    $('.sliderContent table').click(function (e) {
        e.stopPropagation();
    });
    if (lastEle == ele) {
        $('.sliderContent').slideUp('fast');
        $('.sliderContent').parent().parent().removeClass('rowSelected');
        lastEle = null;
        return false;
    }
    lastEle = ele;
    $('.sliderContent').slideUp('fast');
    $('.sliderContent').parent().parent().removeClass('rowSelected');
    $(ele).addClass('rowSelected');
    $(ele).find('.sliderContent').css('left', 21);
    $(ele).find('.sliderContent').css('top', $(ele).offset().top - 38  );
    $(ele).find('.sliderContent').slideDown(400, function () {});
    return false;
}

function saveFileToFolder(ele) {
    var shortUrl = $(ele).closest('.sliderContent').children('.shortUrlHidden').val();
    var folderId = $(ele).val();
    var request = $.ajax({
        url: "http://chillingsafe.com/folder_update.ajax.php",
        type: "POST",
        data: {
            shortUrl: shortUrl,
            folderId: folderId
        },
        dataType: "html"
    });
}
*/
function showAdditionalOptions() {
    if ($('#additionalOptionsWrapper').is(":visible")) {
        $('#additionalOptionsWrapper').slideUp();
    } else {
        $('#additionalOptionsWrapper').slideDown();
    }
}
/* Never used.
function saveAdditionalOptions() {
    fileToEmail = $('#send_via_email').val();
    filePassword = $('#set_password').val();
    processAddtionalOptions();
    showAdditionalOptions();
}
function processAddtionalOptions() {
    if (uploadComplete === false) {
        return false;
    }
    return sendAdditionalOptions();
}
*/
function sendAdditionalOptions() {
    if (fileDeleteHashes.length === 0) {
        return false;
    }
    if ((fileToEmail.length === 0) && (filePassword.length === 0)) {
        return false;
    }
    $.ajax({
        type: "POST",
        url: "http://chillingsafe.com/file_options.ajax.php",
        data: {
            fileToEmail: fileToEmail,
            filePassword: filePassword,
            fileDeleteHashes: fileDeleteHashes,
            fileShortUrls: fileShortUrls
        }
    }).done(function (/* msg */) {
        fileToEmail = '';
        filePassword = '';
    });
}


$(document).ready(function () {
    'use strict';
    /* global updateTotalFilesText, setRowClasses */
    var totalRows;

    $('#fileUpload #fileupload').fileupload({
        sequentialUploads: true,
        url: 'http://chillingsafe.com/upload_handler.php?r=chillingsafe.com&p=http',
        maxFileSize: 268435456 ,
        formData: {
            _sessionid: 'bfeadc6536fe586b347e4c18ced14482'
        },
        xhrFields: {
            withCredentials: true
        },
        maxNumberOfFiles: 100})
        .on('fileuploadadd', function (/* e, data */) {
            $('#fileUpload #fileupload #fileListingWrapper').removeClass('hidden');
            $('#fileUpload #fileupload #initialUploadSection').addClass('hidden');
            $('#fileUpload #fileUploadBadge').addClass('hidden');
            getTotalRows();
            totalRows = getTotalRows() + 1;
            updateTotalFilesText(totalRows);
        })
        .on('fileuploadstart', function (/* e, data */) {
            $('#fileUpload #addFileRow').addClass('hidden');
            $('#fileUpload #processQueueSection').addClass('hidden');
            $('#fileUpload #processingQueueSection').removeClass('hidden');
            $('#fileUpload .cancel').html('<img src="http://cdn.chillingsafe.com/images/pixel.png" style="margin:10px" id="upload-uploading"  />');
            startTime = (new Date()).getTime();
        })
        .on('fileuploadstop', function (e, data) {
            updateTitleWithProgress(100);
            updateProgessText(100, data.total, data.total);
            $('#fileUpload #processQueueSection').addClass('hidden');
            $('#fileUpload #processingQueueSection').addClass('hidden');
            $('#fileUpload #completedSection').removeClass('hidden');
            $('#fileUpload .processingIcon').parent().html('<img src="http://cdn.chillingsafe.com/images/red_error_small.png" width="16" height="16"/>');
            uploadComplete = true;
            sendAdditionalOptions();
            setupCopyAllLink();
        })
        .on('fileuploadprogressall', function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .bar').css('width', progress + '%');
            updateTitleWithProgress(progress);
            updateProgessText(progress, data.loaded, data.total);
        })
        .on('fileuploaddone', function (e, data) {
            fileUrls.push(data['result'][0]['url']);
            fileDeleteHashes.push(data['result'][0]['delete_hash']);
            fileShortUrls.push(data['result'][0]['short_url']);
            var isSuccess = true;
            if (data['result'][0]['error'] !== null) {
                isSuccess = false;
            }
            var html = '';
            html += '<tr class="template-download';
            if (isSuccess === false) {
                html += ' errorText';
            }
            html += '" ';
            if (isSuccess === true) {
                html += 'onClick=""';
            }
            html += '>';
            if (isSuccess === true) {
                html += data['result'][0]['success_result_html'];
            } else {
                html += data['result'][0]['error_result_html'];
            }
            html += '</tr>';
            $(data['context'])
            .replaceWith(html);
        })
        .on('fileuploadfail', function (e, data) {
            $(data['context']).find('.name')
            .html('There was a server problem while attempting the upload, please try again later.');
            totalRows = getTotalRows();
            if (totalRows > 0) {
                totalRows = totalRows - 1;
            }
            updateTotalFilesText(totalRows);
        });
        $('#fileUpload #fileupload #files a:not([target^=_blank])').on('click', function (e) {
            e.preventDefault();
            $('<iframe style="display:none;"></iframe>')
            .prop('src', this.href)
            .appendTo('body');
        });
        $('.showAdditionalOptionsLink').click(function (e) {
            showAdditionalOptions();
            e.preventDefault();
            return false;
        });
});
$(function () {
    $("#tabs").tabs();
    $("#tabs").mouseover(function () {
        $("#tabs").addClass("tabsHover");
    });
    $("#tabs").mouseout(function () {
        $("#tabs").removeClass("tabsHover");
    });
});
/* ============================================================================ */
/* ============================================================================ */
function findUrls(text) {
    var source = (text || '').toString();
    var urlArray = [];
    // var url; Never Used
    var matchArray;
    var regexToken = /(((ftp|https?):\/\/)[\-\w@:%_\+.~#?,&\/\/=]+)|((mailto:)?[_.\w-]+@([\w][\w\-]+\.)+[a-zA-Z]{2,3})/g;
    while ((matchArray = regexToken.exec(source)) !== null) {
        var token = matchArray[0];
        urlArray.push(token);
    }
    return urlArray;
}
/* NOTE:!!!!! Never used  */
function urlUploadFiles() {
    var urlList = $('#urlList').val();
    if (urlList.length === 0) {
        alert('Please enter the urls to start.');
        return false;
    }
    urlList = findUrls(urlList);
    if (urlList.length === 0) {
        alert('No valid urls found, please make sure any start with http or https andtry again.');
        return false;
    }
    if (urlList.length > 5 ) {
        alert('You can not add more than[[[MAX_URLS]]] urls at once.');
        return false;
    }
    var html = '';
    var i;
    for (i = 0; i < urlList.length; ++i) {
        html += '<tr id="rowId' + i + '"><td class="cancel"><a href="#" onClick="return false;"><img src="http://cdn.chillingsafe.com/images/processing_small.gif" class="processingIcon" height="16" width="16" />';
        html += '</a></td><td class="name" colspan="3">' + urlList[i] + '</td></tr>';
    }
    $('#urlUpload #urls').html(html);
    $('#urlUpload #urlFileListingWrapper').removeClass('hidden');
    $('#urlUpload #urlFileUploader').addClass('hidden');
    $('#urlUpload #fileUploadBadge').addClass('hidden');
    function doRequest(url, i) {
        var request = $.ajax({
            url: "http://chillingsafe.com/upload_url",
            type: "POST",
            data: {
                url: url,
                rowId: i
            },
            dataType: "json",
            ysrowId: i,
            xhrFields: {
                withCredentials: true
            }
        });
        request.done(function (data) {
            var isSuccess = true;
            if (data.error !== null) {
                isSuccess = false;
            }
            var html = '';
            html += '<tr class="template-download';
            if (isSuccess === false) {
                html += ' errorText';
            }
            html += '" onClick="">';
            if (isSuccess === false) {
                html += data.error_result_html;
            } else {
                html += data.success_result_html;
                fileUrls.push(data.url);
                fileDeleteHashes.push(data.delete_hash);
                fileShortUrls.push(data.short_url);
            }
            html += '</tr>';
            $('#rowId' + data.rowId).replaceWith(html);
            if (i == urlList.length - 1) {
                $('#urlUpload .fileSectionFooterText').removeClass('hidden');
                sendAdditionalOptions();
                setupCopyAllLink();
            }
        });
        request.fail(function(/*jqXHR, textStatus*/) {
            $('#rowId' + this.ysrowId + ' .cancel .processingIcon').attr('src', 'http://cdn.chillingsafe.com/images/red_error_small.png');
            $('#rowId' + this.ysrowId + ' .name').html(urlList[this.ysrowId] + ' (Failed to request file, possible ajax issue)');
        });

    }
    for (i = 0; i < urlList.length; ++i) {
        doRequest(urlList[i], i);
    }
}
/* ============================================================================ */
/* ============================================================================ */
function CheckTables() {
    $("table ").each(function (/*index*/) {
        $(this).find('tbody:not(:empty)').parent().show();
        $(this).find('tbody:empty').parent().hide();
    });
}
setInterval(CheckTables, 100);
/* ============================================================================ */
/* ============================================================================ */
/* ============================================================================ */

【讨论】:

  • 感谢您的代码,但是 js 中包含了一些 php,我现在已经编辑了主要帖子以显示所有内容。
  • @user3425749:您可能会发现在此处粘贴 JS 代码会很有帮助:jshint.com 理想情况下使用一些插件来一直提示您的代码。我个人在 Vim 中使用它是这样的:technotales.wordpress.com/2011/05/21/node-jslint-and-vim
  • 是的,谢谢,我会用这个,我无法将代码添加到帖子中,所以我把它变成了一个 txt 文件chillingsafe.com/upload.txt
  • 我已经查看并发现了这些问题。六个警告 1 期望一个标识符,而不是看到'
  • @user3425749:它不处理 PHP 代码。如果您的脚本有 PHP 代码,它将尝试将其解释为 Javascript。 而不是看到' 通常用于您的PHP 开始标签。如果是 JS 错误,通常最好查看客户端结果。如果您的编辑器没有正确缩进,请将其放在此处:jsbeautifier.org