【问题标题】:Why is this JQuery Script no longer working on my https Server?为什么这个 JQuery 脚本不再在我的 https 服务器上运行?
【发布时间】:2021-01-09 20:18:45
【问题描述】:

我有这个旧的 jquery 脚本来在网站上显示 Tumblr 帖子。 该脚本在我的 lokal 服务器上运行良好。我什至相信它在 http 上运行良好,但我不确定。然而,在 https 上,脚本不再工作。 这可能是什么原因?

这是脚本:

/**
 * jquery.tumblr.js - jQuery plugin for embedding tumblr posts
 *
 * https://github.com/bicknoyle/jquery.tumblr
 * Copyright (c) 2012 Nick Boyle
 * MIT Licensed
 */
(function( $ ) {
    $.fn.tumblr = function(o)
    {
        var s = $.extend({
            append: false,          // [bool] Append to target container, instead of clearing first
            hostname: null,         // [string] The hostname of your blog (ex: myblog.tumblr.com)
            options: { },           // [object] key:val of options to pass the tumblr API, see http://www.tumblr.com/docs/en/api/v1#api_read for details
            template:'{body}',      // [string or function] template used to construct each post <li> - see code for available {vars}
            type_templates: { }     // [string or function] see below for defaults
        }, o);

        // [string or function] template to be used for each type; these defaults are based on the markup used by the default tumblr theme
        var default_type_templates = {
            answer:'<div class="question">{question}</div><div class="copy">{answer}</div>',
            audio: '<div class="audio">{audio_player}</div><div class="copy"></div>',
            chat:  function(item) {
              str = '<div class="title">{conversation_title}</div><div class="chat"><div class="lines">';
              for(i in item.conversation) { str = str+'<div class="line"><strong>'+item.conversation[i].label+'</strong>'+item.conversation[i].phrase+'</div>' };
              return str+'</div></div>';
            },
            link:  function(item) {
              if( item.link_text ) { return '<div class="link"><a href="{link_url}" target="_blank">{link_text}</a></div><div class="copy">{link_description}</div>' };
              return '<div class="link"><a href="{link_url}" target="_blank">{link_url}</a></div><div class="copy">{link_description}</div>'
            },
            quote:   '<div class="quote">{quote_text}</div><div class="copy">{quote_source}</div>',
            photo:   '<div class="media"><img src="{photo_url_500}" alt="" /></div><div class="copy">{photo_caption}</div>',
            text:    '<div class="title">{regular_title}</div><div class="copy">{regular_body}</div>',
            video:   '<div class="media">{video_player_500}</div><div class="copy">{video_caption}</div>'
        };
        s.type_templates = $.extend(default_type_templates, s.type_templates);

        function extract_relative_time(date)
        {
            var toInt = function(val) { return parseInt(val, 10); };
            var relative_to = new Date();
            var delta = toInt((relative_to.getTime() - date) / 1000);
            if (delta < 1) delta = 0;
            return {
              days:    toInt(delta / 86400),
              hours:   toInt(delta / 3600),
              minutes: toInt(delta / 60),
              seconds: toInt(delta)
            };
        }

        function format_relative_time(time_ago)
        {
            if ( time_ago.days > 2 )     return 'about ' + time_ago.days + ' days ago';
            if ( time_ago.hours > 24 )   return 'about a day ago';
            if ( time_ago.hours > 2 )    return 'about ' + time_ago.hours + ' hours ago';
            if ( time_ago.minutes > 45 ) return 'about an hour ago';
            if ( time_ago.minutes > 2 )  return 'about ' + time_ago.minutes + ' minutes ago';
            if ( time_ago.seconds > 1 )  return 'about ' + time_ago.seconds + ' seconds ago';
            return 'just now';
        }

        /**
         * Prepare the data for each posts, for use by the user in the template
         */
        function prepare_template_data(item)
        {
            var o = {};

            /**
             * Change keys from two-words to two_words
             */
            var key_regex = new RegExp('-','g');
            $.each(item, function(key,val) {
                o[key.replace(key_regex, '_')] = val;
            });

            // "text" is referred to by API output as "regular"????
            if( item.type == 'regular' ) { o.type = 'text'; }
            // "chat" is referred to by API output as "conversation"????
            if( item.type == 'conversation' ) { o.type = 'chat'; }

            /**
             * Add some custom vars that may be handy for the user
             */
            o.relative_time = format_relative_time(extract_relative_time(Date.parse(o.date)));
            o.reblog_url = 'http://www.tumblr.com/reblog/'+o.id+'/'+o.reblog_key;

            /**
             * Create body, based on the type_template for that
             * media type.
             */
            o.body = t(s.type_templates[o.type], o);
            return o;
        }

        // Expand values inside simple string templates with {placeholders}
        function t(template, info) {
            var result;
            if ( typeof template === 'string' || typeof template === 'number' ) {
                result = template;
            }
            else {
                result = template(info);
            }


            $.each(info, function(key, val) {
                result = result.replace(new RegExp('{'+key+'}','g'), val === null ? '' : val);
            });
            return result;
        }
        // Export the t function for use when passing a function as the 'template' option
        $.extend({tumblr: {t: t}});

        /**
         * Get data from tumblr, listify it, and load it into the widget
         */
        var target_selector = this;
        $.getJSON('http://'+s.hostname+'/api/read/json?callback=?', s.options, function(response) {
            var list = $('<ul class="post_list">');
            var posts = $.map(response.posts, prepare_template_data);
            //posts = $.grep(posts, s.filter).sort(s.comparator).slice(0, s.count);//TODO: Implement
            list.append($.map(posts, function(o) { return '<li>' + t(s.template, o) + '</li>'; }).join('')).
              children('li:first').addClass('post_first').end().
              children('li:odd').addClass('post_even').end().
              children('li:even').addClass('post_odd');
            if( !s.append ) {
                target_selector.empty()
            }
            target_selector.append(list).trigger('tumblr:load');
        });
        return target_selector;
    }
})( jQuery );

我很感激你们所有的 cmets! 费利克斯

【问题讨论】:

  • 不久前 tumblr 停止允许更新仍然包含 http 资源的主题,您需要通过 https 访问所有内容,我认为对于大多数东西来说这很好,因为世界其他地方已经转移到 https差不多。通常只需将 s 放在 http 后即可确认资源可用,否则只需将代码粘贴到模板中即可。你可以使用javascript-minifier.com 或类似的方法来缩小它,它只有 130 多行未压缩的代码,所以不是什么大问题。
  • 实际上再看一遍,可能会有修复,如果您可以验证它在任何环境中都可以使用,那将很有用,而且尝试跨不同协议时应该有一些控制台错误,我会尝试写一些应该给出可能答案的东西,至少是一些可以尝试的东西。
  • 您好 Iharby,感谢您的回复。 “它适用于任何环境”是什么意思?我该如何测试呢?我想运行的文件可以在这里找到:github.com/alexhayes/jquery-tumblr
  • 对不起,我的意思是协议而不是环境。在您的问题中,您写了“该脚本在我的本地服务器上对我很有效。我什至相信它在 http 上运行良好,所以我认为它可以在一个协议上运行?

标签: jquery tumblr


【解决方案1】:

我不确定这是否可行,但您可以尝试使用相同的协议,具体取决于您所在的服务器(localhost、https 等)

而不是这个:

$.getJSON('http://'+s.hostname+'/api/read/json?callback=?', s.options, function(response) {

怎么样

var protocol = document.location.protocol;
$.getJSON(protocol + s.hostname+'/api/read/json?callback=?', s.options, function(response) {

这意味着如果您的代码在 localhost 中运行,则协议将为 http,但如果您在安全服务器上运行,则协议将为 https。

问题可能是你根本无法通过 http 发出请求,我不知道 100%,所以你需要测试一下。

【讨论】:

  • 您好,感谢您的回复。不幸的是,当我更改代码时,屏幕保持空白。
  • 如果您想查看代码 - 这是完全相同的脚本,只是不再在我的服务器上运行:github.com/alexhayes/jquery-tumblr
  • 我要发布另一个答案,我怀疑这是基于的代码很旧。
【解决方案2】:

好的,下载 github repo 代码后,我在这里做了一个工作示例: https://jsfiddle.net/lharby/2dxcL536/

我在脚本窗口的顶部包含了jquery.tumblr.js,底部是实际的函数调用。

我已将此调用更改为 https,现在至少该函数正在进行 api 调用(顺便说一下,在 localhost 中,这仅适用于 http)

$('#posts')
    .tumblr({
    url:        'https://blog.thehiddenventure.com', // was previously http
    pagination: '#pagination',
    loading:    '#loading'
});

但是代码似乎还有其他错误。

如果您运行它并打开网络面板,您可以看到从调用中检索到的项目。

这是 json 响应:https://blog.thehiddenventure.com/api/read/json?start=0&num=20&_=1613389676379 这意味着应该可以从该响应构建代码(这是这个库的目的,但正如我所说,我认为它已经过时了)。你可以自己动手。

更新 好的,错误是由一个名为 timeago 的函数引发的,所以我将其设置为 false,它现在正在 jsfiddle 中输出数据(尽管控制台中还有其他错误)。

改变

'timeago'            : false,

在jquery.tumblr.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-07
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多