• 定期自动更新Js文件

    by{ guangboo }, published {2009-10-12}, Tag { Javascript / asp.net / }

    js文件大部分是起到存储js库,js函数等的功能,很少用于存储数据;特别情况下,如使用AJAX技术的时候会将数据序列号成JSON对象,并以application/javascript的Content-type返回给客户端,功能客户端js库解析。此时的数据就好像是js文件。

    案例:

    某券商,部门A负责网站的代销基金数据更新,部门B负责维护网站(包括代销基金栏目);网站初期开了代销基金更新周期较短,故代销基金栏目做成html文件,如有更新就从部门A整理的数据中,修改该html文件;由于工作量较少,一直没有出现什么问题,现在代销基金列表需要“单位净值”,“累计净值”,“基金类型”等,由于“单位净值”,“累计净值”的更新周期一般为一天,故需读取数据库,然而开发后台又比较麻烦,希望将数据保存在js文件中,每天自动更新js文件就可以了。

    解决方案:

    1. 固定每天访问当天最新的js文件,js文件以日期命名,如“funds-2009-10-12.js”;

    2. 每天第一次访问的时候,当天的js文件是不存在的,需要创建,然后删除过时的js文件。

    3. 当天的其他对该js文件的请求都定位到当天的js文件上,如果该文件不存,视为该请求为当天第一个请求,处理参照2。

    示例代码:

    DateTime now = DateTime.Now;
    string rootDir = AppDomain.CurrentDomain.BaseDirectory;
    // 最新js文件
    string newJsFileName = "fundvalues-" + now.ToString("yyyy-MM-dd") + ".js";
    string jsFilePath = rootDir + newJsFileName;
    
    try {
        FileInfo file = new FileInfo(jsFilePath);
        // 不存在就重新获取今天最新的数据创建该js文件
        if(!file.Exists) {
           string result = "test"; // 存储数据库获取的数据
            StreamWriter writer = null;
            try {
                writer = file.CreateText();
                writer.Write(result);
            } catch(Exception ex) {
                // 处理异常
            } finally { writer.Close(); }
        }
        // 删除以前的老js文件
        // 忽略异常
        string[] oldJsFiles = Directory.GetFiles(rootDir, "fundvalues-*.js", SearchOption.TopDirectoryOnly);
        StringBuilder sbErr = new StringBuilder();
        if(oldJsFiles.Length > 0) {
            try {
                foreach(string path in oldJsFiles) {
                    if(path.ToLower() != jsFilePath.ToLower()) {
                        File.Delete(path);
                    }
                }
            } catch(Exception ex0) {
                // 忽略异常
            }
        }
    } catch(Exception ex) {
        // 处理异常
    }
    // 返回js文件
  • Window.Open的使用方法

    by{ guangboo }, published {2009-09-01}, Tag { Javascript / }

    语法:

    window.open(url[, windowName[, windowFeatures]])

    url:要打开的URL地址;
    windowName:打开窗口的名称,可以之后使用;
    windowFeatures:打开窗口的属性。

    打开一个标准窗口的代码如下:

    window.open('http://www.klipdas.com', 'newWindow');

    可以通过第三个参数来控制打开窗口的属性,属性包括,location,status,width,height,scrollbars,toolbar,menubar,directories,resizable。

    status 窗口下方的状态栏.
    toolbar 浏览器标准工具栏包括返回前进按钮
    location 地址栏
    menubar 窗体菜单栏
    directories 浏览器标准文件按钮
    resizable 是否允许用户修改窗口大小.
    scrollbars 如果窗体内容超出范围是否显示滚动条
    height 指定窗体的高度,单位px
    width 指定窗体的宽度,单位px

    使用实例:

    window.open('http://www.klipdas.com', 'newWindow', 'width=400,height=300,menubar=1,location=0,scrollbar=1');

    打开一个空的新窗口并往新窗口里面添加内容。

    var win = window.open('', 'win', 'location=0,menubar=0,status=0');
    win.document.write('

    Hello world!

    ');
  • Improving Django Comments’ User Experience With Ajax

    by{ guangboo }, published {2009-07-05}, Tag { Django / Javascript / Ajax / }

    I really like Django. It is not bloated like a lot of other frameworks, and it has a healthy balance between convention and configuration. As a developer I want to be able to use the tools that I want to use, and not be forced into a specific way of doing things. An example of this in Django is the comments framework that is part of django.contrib. The comments framework provides the infrastructure for attaching comments to any domain model in your Django project through content types. It also provides a few spam prevention features that you should consider leveraging, such as a security hash or a hidden honeypot field. However, the default comments form is rather bare, and the workflow for posting a comment requires too many clicks and redirects.

    There are some solutions that try to improve the user experience, and do a good job of it, but require hacking the comments framework. I personally don’t like hacking the internals of any framework. Not because I’m scared to, but because I don’t want to inherit any unnecessary maintenance overheads.

    Besides, I believe the comments framework does the right thing. It doesn’t try to do too much, and by that I mean the HTML that it generates for the default rendered form and corresponding responses can easily be mashed up as part of the submitting pages DOM. So with a bit of JQuery and AJAX knowhow you can post comments without refreshing or being redirected away from the submitting page.

    First I use the utility methods from the comments framework to list all comments for a particular discussion content type, and to display the default comment form immediately after. Note that the comment form is wrapped in div tags with the id “comment_form”. The div will be used to override the block with responses from the server after an ajax post.

    In my template (discussion.html) in which I want to allow people to comment on something I add the following to a script block that will insert the JavaScript into the head element of the base template (base.html).

    
    

    In line 2 I define a method called bindPostCommentHandler() which performs the ajax call to post a comment and to handle the response when the form submit event is triggered.

    In line 3 I remove the preview button from the form as I do not want this functionality. Rich text plugins generally have a preview mode, so I don’t see the need for the server to process a preview request.

    In line 4 I bind the ajax post call to the submit event of the comments form. This means when I click on the Post button to submit the form I will trigger an ajax post instead of a normal post to the server.

    Line 7 serialises the data from the form input fields using the JQuery serialize() function.

    Line 8 specifies the URL to post to. I use the utility method from the comments framework to retrieve this for me, so I don’t need to hard code it to a specific URL. The comment_form_target should retrieve the correct URL for the comments application that you should have configured in your urls.py file. If not then add the following URL route to your urls.py file.

        (r'^comments/', include('django.contrib.comments.urls')),
    

    Line 10 specifies that the response will be HTML. This is necessary so that JQuery knows how to parse and handle the response.

    Line 11 details the success callback, which is the function that calls when the response is successful. The callback simply replaces the form in the div wrapper with the response. A successful response could either be a “thank you” message for posting a comment, or a form displaying fields with invalid fields. Line 13 is necessary to rebind the bindPostCommentHandler() function to any new form that appears in the div wrapper. If you omit this rebinding, then you will lose ajax posts on successive submits.

    Line 15 defines the callback that gets called when the server responds with an http error code. I just override the div wrapper block with an apologetic message.

    Finally, line 23 binds the bindPostCommentHandler() function when the page is ready.

    As you can see from the above, all you need is some JavaScript to improve the user experience for posting comments using Django’s comments framework. No framework hacking necessary. Note that if you want to further improve this solution, then you can add sliders, fade ins, and fade outs for displaying the responses from the server. I left these out for brevity. I also left out appending the submitted comment to the list of comments, as the above solution will only display the submitted comment after the user performs a GET request after the submit.

  • Mime Type With Javascript----Text/Javascript,Application/Javascript, And Appliation/X-Javascript

    by{ guangboo }, published {2009-04-30}, Tag { Javascript / }

    这两天使用iewatch观察google的网站的时候,发现学到js文件的mime类型为text/javascript,而今天在qq的网站上,使用iewatch发现,有时用text/javascript的,也有使用application/javascript的还有使用appliation/x-javascript的,所有就不太知道这三个mime 类型有什么区别,在google上一搜:

    The traditional MIME type for JavaScript programs is
    "text/javascript". Another type that has been used is
    "application/x-javascript" (the "x" prefix indicates that it is an
    experimental, nonstandard type). RFC 4329 standardized the
    "text/javascript" type because it is in common use. However, because
    JavaScript programs are not really text documents, it marks this type
    as obsolete and recommends "application/javascript" (without the "x-")
    instead. At the time of this writing, "application/javascript" is not
    well supported, however. That might be the reason why
    "application/x-javascript" is used by a lot of webpages.

    大致意思是:传统的javascript程序的MIME类型是“text/javascript”,其他使用的还有"application/x-javascript"(x前缀表示这是实验性的,不是标准的类型),RFC4329规定了“text/javascript”类型,因为它普遍被使用。然而,javascript程序并不是真正的文本文件,这就表示这个类型已经意味着过时了,而推荐使用"application/javascript"(去除x前缀)。然而,在写程序的时候,"application/javascript"没有很好的支持。这也行就是"application/x-javascript"被使用在很多网页中的原因。

  • Dynamically Loading An External Javascript Or Css File

    by{ guangboo }, published {2007-11-22}, Tag { Javascript / css / HTML / }
    <head>
        <link type="text/css" rel="stylesheet" href="style/style.css"/>  
        <script type="text/javascript" src="js/jsFile.js"></script>
    </head>
    

    We commonly load external javascript (*.js) or css (*.css) file on the page with the above way,doesn't we? Actually, we can make use of javascript and DOM implementing dynamically loading those files.We can use operating DOM method to achieve it.For example, load an external javascript file and an external css file with the following function.

     

    function requireFile(fileName, fileType){
        var ref;
        if(fileType == "js"){
            ref = document.createElement("script");
            ref.setAttribute("type", "text/javascript");
            ref.setAttribute("src", fileName);
        }
        if(fileType == "css"){
            ref = document.createElement("link");
            ref.setAttribute("type", "text/css");
            ref.setAttribute("rel", "stylesheet");
            ref.setAttribute("href", fileName);
        }
        document.getElementsByTagName("head")[0].appendChild(ref);
    }
    

    Then. we can use requireFile("js/js.js", "js") to dynamically load js/js.js file or requireFile("style/style.css", "css") to dynamically load style.css file.

    That's OK!