標籤: ajax

  • JSONP 實做:使用 Google Ajax Search

    範例網頁:JSONP 實做:使用 Google Ajax Search

    Google Ajax Search with JSONP

    ※ 詭異的是,我使用 $.get 都只能收到 400 Bad Request,只能用 $.ajax 才能正常。

    $.ajax({
          url: 'http://ajax.googleapis.com/ajax/services/search/web',
          data:{
            'key': gsearch.key,
            'v': '1.0',
            'q': encodeURIComponent(k), // + '+site:essoduke.org' 搜尋網站,
            'rsz': 'large',
            'hl': 'zh-TW',
            'start': s
          },
      		dataType: 'jsonp',
      		success: gsearch.fetch
        });
    

    參考資料:

  • Multiple File Upload by AjaxFileUpload of jQuery

    AjaxFileUpload 是 jQuery 的擴充套件之一,可以使用 Ajax 來即時上傳檔案,不過缺點就是一次只能上傳一個。

    但是今天在研究 Multiple File Upload 搭配 AjaxFileUpload 時,找到一個土法煉鋼的方式可以達成一次上傳多個檔案。

    這是 AjaxFileUpload 原本的使用方法:

    $.ajaxFileUpload ({
            url:'doajaxfileupload.php',
            secureuri:false,
            fileElementId:'fileToUpload',
            dataType: 'json',
            success: function (data, status){
                if(typeof(data.error) != 'undefined'){
                    if(data.error != ''){
                        alert(data.error);
                    }else{
                        alert(data.msg);
                    }
                }
            },
            error: function (data, status, e){
                alert(e);
            }
    });
    

    土法煉鋼法就是利用 Multiple File Upload plugin 所建立的 Array 讓上述過程跑 n 次… XD

    //取得 uploads 表單內,input 類型為 file 表單元素並依序執行迴圈
    $('input:file', $('#uploads')).each(function(){
      $.ajaxFileUpload({
            url:'doajaxfileupload.php',
            secureuri:false,
            //重點就是這行,依序傳入 file 表單元素的 id 值
            fileElementId:$(this).attr("id"),
            dataType: 'json',
            success: function (data, status){
              //後端處理回傳 json...
            },
            error: function (data, status, e){
                alert(e);
            }
        });
    });
    

    目前測試使用上都沒有問題,下一個實做就是要像 GMail 的夾帶檔案一樣,讓已選取上傳的檔案清單可以在點選 remove 時移出清單,同時也刪除已上傳的檔案…

    DEMO 測試

    延伸閱讀:

  • form preview within Thickbox via Ajax

    突然想研究用 Thickbox 搭配 Ajax 來達成表單預覽的功能,就動手實作了一下。

    jQuery Ajax

    var url = "preview.php?" + new Date().getTime();
    $.post(url, {c: $("#content").val()},
          function(result){
            $("#preview_temp").html(result);
            tb_show('caption', '#TB_inline?height=480&width=640&inlineId=preview_temp', false);
          }
    );
    

    流程其實很簡單,就是把結果 post 到後端處理的程式,再把結果 callback 到頁面元素就行了,會用 post 就是不用受限於 get 的 2KB 限制。

    整個流程的重點在於「如何在 javascript 中呼叫 Thickbox」,方法就是直接使用 tb_show 函式,把 url 直接替換成呼叫 inline 的方式即可:

    //tb_show('Your Caption', href, group);
    tb_show('caption', '#TB_inline?height=480&width=640&inlineId=preview_temp', false);
    

    Demo: form preview within Thickbox via Ajax

    其實試出來以後才想到包括 tinyMCE 等 Rich Text Editor 早就都提供預覽的功能了。

    原來這就是吃飽太閒嗎?XD

    —
    話說…最近正在瘋狂使用 jQuery 來虐待自己!