无法找到jqueryFileTree连接器脚本

时间:2014-05-12 18:10:09

标签: javascript jquery python node.js filetree

我正在尝试创建一个显示文件树的网页。我选择使用此网站上的jqueryFileTree:http://www.abeautifulsite.net/blog/2008/03/jquery-file-tree/

最终,我将把这棵树挂到服务器上。但是,现在,我正在尝试在运行Node.js localhost的Windows机器上运行它。

由于这个jquery插件需要使用连接器脚本(为了能够提取目录信息),我选择使用它们包含的python连接器脚本jqueryFileTree.py。

我的问题是localhost告诉我无法找到python脚本(错误404)。但是,我知道我已经为文件提供了正确的路径,因为当我将URL输入浏览器时,我可以下载脚本。这种行为让我失望,因为它告诉我一件事,但做另一件事。

以下是我的所有相关代码和信息。

目录结构:

|-public (localhost)
 |-connectors
  |-jqueryFileTree.py

创建jqueryFileTree对象:

$(window).load(
function()
{
    $('#fileTree').fileTree({
        root: '/',
        script: 'connectors/jqueryFileTree.py',
        expandSpeed: 500,
        collapseSpeed: 500,
        multiFolder: true
    },
    function(file)
    {
        alert(file);
    });
});

这是我的错误消息:

Failed to load resource: the server responded with a status of 404 (Not Found): http://localhost:3700/connectors/jqueryFileTree.py

以下是jqueryFileTree和连接器脚本的代码。我没有写代码。当你从我之前提到的网站下载插件时,就会发生这种情况。

插件代码:

// jQuery File Tree Plugin
//
// Version 1.01
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 24 March 2008
//
// Visit http://abeautifulsite.net/notebook.php?article=58 for more information
//
// Usage: $('.fileTreeDemo').fileTree( options, callback )
//
// Options:  root           - root folder to display; default = /
//           script         - location of the serverside AJAX file to use; default = jqueryFileTree.php
//           folderEvent    - event to trigger expand/collapse; default = click
//           expandSpeed    - default = 500 (ms); use -1 for no animation
//           collapseSpeed  - default = 500 (ms); use -1 for no animation
//           expandEasing   - easing function to use on expand (optional)
//           collapseEasing - easing function to use on collapse (optional)
//           multiFolder    - whether or not to limit the browser to one subfolder at a time
//           loadMessage    - Message to display while initial tree loads (can be HTML)
//
// History:
//
// 1.01 - updated to work with foreign characters in directory/file names (12 April 2008)
// 1.00 - released (24 March 2008)
//
// TERMS OF USE
//
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC.
//
if(jQuery) (function($){

    $.extend($.fn, {
        fileTree: function(o, h) {
            // Defaults
            if( !o ) var o = {};
            if( o.root == undefined ) o.root = '/';
            if( o.script == undefined ) o.script = 'jqueryFileTree.py';
            if( o.folderEvent == undefined ) o.folderEvent = 'click';
            if( o.expandSpeed == undefined ) o.expandSpeed= 500;
            if( o.collapseSpeed == undefined ) o.collapseSpeed= 500;
            if( o.expandEasing == undefined ) o.expandEasing = null;
            if( o.collapseEasing == undefined ) o.collapseEasing = null;
            if( o.multiFolder == undefined ) o.multiFolder = true;
            if( o.loadMessage == undefined ) o.loadMessage = 'Loading...';

            $(this).each( function() {

                function showTree(c, t) {
                    $(c).addClass('wait');
                    $(".jqueryFileTree.start").remove();
                    $.post(o.script, { dir: t }, function(data) {
                        $(c).find('.start').html('');
                        $(c).removeClass('wait').append(data);
                        if( o.root == t ) $(c).find('UL:hidden').show(); else $(c).find('UL:hidden').slideDown({ duration: o.expandSpeed, easing: o.expandEasing });
                        bindTree(c);
                    });
                }

                function bindTree(t) {
                    $(t).find('LI A').bind(o.folderEvent, function() {
                        if( $(this).parent().hasClass('directory') ) {
                            if( $(this).parent().hasClass('collapsed') ) {
                                // Expand
                                if( !o.multiFolder ) {
                                    $(this).parent().parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
                                    $(this).parent().parent().find('LI.directory').removeClass('expanded').addClass('collapsed');
                                }
                                $(this).parent().find('UL').remove(); // cleanup
                                showTree( $(this).parent(), escape($(this).attr('rel').match( /.*\// )) );
                                $(this).parent().removeClass('collapsed').addClass('expanded');
                            } else {
                                // Collapse
                                $(this).parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
                                $(this).parent().removeClass('expanded').addClass('collapsed');
                            }
                        } else {
                            h($(this).attr('rel'));
                        }
                        return false;
                    });
                    // Prevent A from triggering the # on non-click events
                    if( o.folderEvent.toLowerCase != 'click' ) $(t).find('LI A').bind('click', function() { return false; });
                }
                // Loading message
                $(this).html('<ul class="jqueryFileTree start"><li class="wait">' + o.loadMessage + '<li></ul>');
                // Get the initial file list
                showTree( $(this), escape(o.root) );
            });
        }
    });

})(jQuery);

连接器脚本代码:

#
# jQuery File Tree
# Python/Django connector script
# By Martin Skou
#
import os
import urllib

def dirlist(request):
   r=['<ul class="jqueryFileTree" style="display: none;">']
   try:
       r=['<ul class="jqueryFileTree" style="display: none;">']
       d=urllib.unquote(request.POST.get('dir','c:\\temp'))
       for f in os.listdir(d):
           ff=os.path.join(d,f)
           if os.path.isdir(ff):
               r.append('<li class="directory collapsed"><a href="#" rel="%s/">%s</a></li>' % (ff,f))
           else:
               e=os.path.splitext(f)[1][1:] # get .ext and remove dot
               r.append('<li class="file ext_%s"><a href="#" rel="%s">%s</a></li>' % (e,ff,f))
       r.append('</ul>')
   except Exception,e:
       r.append('Could not load directory: %s' % str(e))
   r.append('</ul>')
   return HttpResponse(''.join(r))

我可能发布了超过需要的内容。我想要彻底而不是必须回复和编辑更多信息。话虽如此,请随时询问更多信息。

我感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

尝试一件事:使用此路径'connectors / jqueryFileTree.py'尝试使用浏览器中的绝对URL来下载脚本。

答案 1 :(得分:0)

请原谅我没有查看您的脚本并提供延迟回复。但是,我遇到了同样的问题并相信通过遵循以下所述的路径解决了问题:http://pastebin.com/kVkTssdGhttp://www.abeautifulsite.net/jquery-file-tree/

详细说明: 1)我创建了一个名为&#39; jQFTree&#39;的新文件夹。在我的项目的node_modules&#39;子文件夹。 2)我包括行:

var jQFTree=require('jQFTree');

app.post('/FileTree', jQFTree.handlePost);

到node.js中的app.js文件 3)添加到我的表格&nbsp; html:

div(id="FileTree" class="fTre")
分别是

和脚本:

var orig = window.location.origin + '/FileTree';
var servDir='Mats';//or Carps or Rugs
$("#FileTree").fileTree({
    root: servDir,
    script: orig
},
followed by callback function.

4)之前创建的jQFTree文件夹只包含一个名为&#39; index.js&#39;以下javascript代码:

//my Node.js module for jQuery File Tree
var path = require('path'); 
var fs = require('fs');
var util = require('util');
var stringHeader = "<ul class='jqueryFileTree' style='display: none;'>";
var stringFooter = "</ul>";
// arguments: path, directory name
var formatDirectory = 
    "<li class='directory collapsed'><a href='#' rel='%s/'>%s</a><li>";
// arguments: extension, path, filename
var formatFile = "<li class='file ext_%s'><a href='#' rel='%s'>%s</a></li>";
var createStatCallback = (function (res, path, fileName, isLast) {
    return function (err, stats) {
        if (stats.isDirectory()) {
            res.write(util.format(formatDirectory, path, fileName));
        }
        else {
            var fileExt = fileName.slice(fileName.lastIndexOf('.') + 1);
            res.write(util.format(formatFile, fileExt, path, fileName));
        }
        if (isLast) {
            res.end(stringFooter);
        }
    }
});

exports.handlePost = function (req, res) {
    //for safety; only directory name is available from the browser 
    //through the req.body.dir variable
    //but complete dir path in server is required for dir browsing
    // 'text/html'
    //console.log('Filetree handles post dir: '+ req.body.dir);
    res.writeHead(200, { 'content-type': 'text/plain' });
    res.write(stringHeader);
    // get a list of files
    var seeDir = req.body.dir;
    if (seeDir.indexOf('%5C') > -1 || seeDir.indexOf('%2F') > -1) {
        //directory path was returned as a subfolder from jQuery FileTree using URL encoding
        //decode it first:
        seeDir = decodeURIComponent(seeDir);
        //console.log('seeDir: '+seeDir+' __dirname:'+__dirname);
        if (seeDir.slice(-1) == "/" || seeDir.slice(-1) == "\\") {
            //last char either / (MS-windows) or \ (not MS-windows) is dropped
            seeDir = seeDir.slice(0, seeDir.length - 1)
            if (seeDir.indexOf('/') > -1) {
                seeDir = seeDir + '/';
            }
            else {
                seeDir = seeDir + '\\';
            }
        }
    }
    if (req.body.dir == 'Mats' || req.body.dir == 'Carps' || req.body.dir == 'Rugs') {
        //restricted to three sub dirs in server directory: public/MatsCarpsRugs/
        //console.log('.=%s', path.resolve('.'));
        //gives path to the above app.js calling this module (=as wanted)
        //combine path to requested directory:
        seeDir = path.join(path.resolve('.'), 'public', 'MatsCarpsRugs', req.body.dir);
        if (seeDir.indexOf('/')>-1){
            //web-browser not in ms-windows filesystem
            seeDir=seeDir+'/';
        }
        else{
            //web-browser is in ms-windows filesystem
            seeDir=seeDir+'\\';
        }
        //console.log('seeDir now: '+seeDir);
    }
    fs.readdir(seeDir, function (err, files) {
        var fileName = '';
        var path = '';
        var statCallback;
        if (files.length === 0) {
            path = util.format('%s%s', seeDir, fileName);
            statCallback = createStatCallback(res, path, fileName, true);
            fs.stat(path, statCallback);
            }
        for (var i = 0; i < files.length; i++) {
            fileName = files[i];
            path = util.format('%s%s', seeDir, fileName);
            var isLast = (i === (files.length - 1));
            statCallback = createStatCallback(res, path, fileName, isLast);
            fs.stat(path, statCallback);

        }
    });
}

我希望这可以帮助您或其他人找到解决方案

答案 2 :(得分:0)

我认为你的问题在于:

script: 'connectors/jqueryFileTree.py',

您的javascript在前端(用户浏览器)上执行,无法查看python文件(在服务器上)。

相反,您应该放置Django视图可用的URL。检查Django网址路由机制(https://docs.djangoproject.com/en/1.11/topics/http/urls/)以查找与您的视图相关联的网址(“dirlist”)。