使函数在HTTP和HTTPS中工作

Making a function work in HTTP and HTTPS

本文关键字:HTTPS 工作 HTTP 函数      更新时间:2023-09-26

我有从另一个开发人员那里继承的Javascript代码。我对Javascript很陌生。

我遇到的问题是,当用户在HTTPS中时,它将无法正常工作。有解决此问题的方法吗?

var tier1CategoryLink = "http://" + window.location.hostname + "/categories/";
    $("#as_Placeholder").load(tier1CategoryLink + " .SubCategoryList > ul", function(){
        $('#tier1').find('option').remove().end().append('<option>Make</option>');
        $("#as_Placeholder ul li").each(function(){
            var thisText = $(this).children("a").text();
            if ((thisText != "All Products") && (thisText != "Best Selllers") && (thisText != "Chromoly Flywheel Combo Sale") && (thisText != "New Arrivals") && (thisText != "On Sale") && (thisText != "Needs Categories")) {
                $("#tier1").append("<option value='" + $(this).children("a").attr("href") + "'>" + thisText + "</option>");
            }
        });
    });

使用 window.location 确定用户的当前协议并相应地进行调整:

var tier1CategoryLink = window.location.protocol + "//" + window.location.hostname + "/categories/";

或者只使用相对网址:

var tier1CategoryLink = "/categories/";

我想你想说你在浏览器中遇到了一个java脚本错误。这也是意料之中的。当用户在https中时,您必须修改java脚本以包含https。例如,您的第一行必须如下所示:

var tier1CategoryLink = "https://" + window.location.hostname + "/categories/";

编辑:此外,您可以查看此内容以解决您的问题。检测HTTP或HTTPS,然后在JavaScript中强制HTTPS

最简单的解决方案是只使用双斜杠

var tier1CategoryLink = "//" + window.location.hostname + "/categories/";

规范第 5.2 节中的详细信息