顯示具有 ASP 標籤的文章。 顯示所有文章
顯示具有 ASP 標籤的文章。 顯示所有文章

2014年1月14日 星期二

jQuery.ajax 傳遞中文變亂碼

今天用 2 支 asp 測試 jQuery.ajax 傳遞中文
就出現亂碼問題
在這記錄一下
架構是 a.asp 透過 jQuery.ajax 呼叫 b.asp

a.asp
<html>
   <head>
      <meta HTTP-EQUIV="Content Type" CONTENT="text/html; charset=big5">
      <script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
      <script>
         $(function(){
            $("#btnSend").on("click",function(){
               $.ajax({
                  async:false,
                  type:"POST",
                  data:{name : $("#tInput").val()},
                  dataType:"text",
                  url:"b.asp",
                  success:function(msg){$("#sMessage").text(msg);},
                  error:function(xhr,status,thrown){alert(thrown);}
               });
            });
         });
      </script>
   </head>
   <body>
      <input type="text" id="tInput">
      <input type="button" id="btnSend" value="Send"><br>
      <span id="sMessage"></span>
   </body>
</html>

b.asp
<%=request.form("name") & " 您好~" %>

在 tInput 中輸入 "某甲"
結果 span 中顯示 "?�甲 �z�n~" 的亂碼

查了一堆資料
才知道原來 jQuery.ajax 預設會將 data 以 utf-8 方式編碼後送出
(contentType 預設為 "application/x-www-form-urlencoded; charset=UTF-8"
 詳見 : jQuery)

所以只要在 b.asp 加入一行 <%session.codepage=65001%>
即可解決亂碼問題
<%session.codepage=65001%>
<%=request.form("name") & " 您好~" %>

關於 session.codepage 的詳細說明請見 : 藍色小舖 (#3老頑童大大的說明)

2013年10月25日 星期五

ASP(vbscript) Querystring 判斷

記錄一下 ASP(vbscript) Querystring 的判斷結果
<%
   if IsEmpty(Request("a")) then
      ' http://localhost/TestQueryString.asp
      response.write "Empty"
   end if

   if IsNull(Request("a")) then
      response.write "Null"
   end if

   if Request("a") = "" then
      ' http://localhost/TestQueryString.asp
      ' http://localhost/TestQueryString.asp?a
      ' http://localhost/TestQueryString.asp?a=
      response.write "Blank"
   end if

   if IsNumeric(Request("a")) then
      ' http://localhost/TestQueryString.asp
      ' http://localhost/TestQueryString.asp?a=123
      ' http://localhost/TestQueryString.asp?a=-123
      ' http://localhost/TestQueryString.asp?a=0.123
      ' http://localhost/TestQueryString.asp?a=-0.123
      response.write "Numeric"
   end if

   if Request("a") is nothing then
      response.write "Nothing"
   end if
%>

2012年2月15日 星期三

ASP submit 後中文變亂碼

最近寫了一支 ASP
submit form 之後
所有中文都變成亂碼

試了很久, 最後終於解決
只要在一開始加上一行
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>

2011年9月14日 星期三

ASP 呼叫 .NET Web Service

為了讓 ASP 呼叫 .NET 的 Web Service
上網查了好久的資料
查到有 2 種方式可以達成
   1. 使用 XMLHTTP 呼叫
   2. 使用 SOAP 呼叫
最後決定用 XMLHTTP 的方式呼叫
因為 SOAP 要另外在 ASP 端安裝 SOAP Toolkit

在這邊記錄一下 XMLHTTP 呼叫 Web Service 的方法

<%
   Set objHttp = Server.CreateObject("MSXML2.XMLHTTP")
   Set xmlDOC = Server.CreateObject("MSXML.DOMDocument")

   ' Web Service 網址 (最後面加要呼叫的Function Name)
   ws_url = "http://localhost/TestWebService/Service.asmx/Add"

   ' Web Service 要傳入的參數
   ws_params = "Param1=" & 1 & "&Param2=" & 3

   ' Web Service 的 web.config 要在 <system.web> </system.web> 中設定
   ' <webservices>
   '    <protocols>
   '        <add name="HttpPost"/>
   '        <add name="HttpGet"/>
   '    </protocols>
   ' </webServices>
   objHttp.Open "POST", ws_url, False
   objHttp.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
   objHttp.Send(ws_params)
   xmlDOC.load(objHttp.responseXML)

   if objHttp.Status = 200 then
      xmlStr = xmlDOC.xml
      Response.Write Replace(Replace(xmlStr,"<","&lt;"),">","&gt;")
   else
      Response.Write "Error : " & objHttp.StatusText & "(" & objHttp.Status & ")"
   end if
%>

2010年8月31日 星期二

ASP 操作 Excel 簡單範例 (三)

補充一些小東東

<%
   '// A1~C1 合併放入 "Header" 字樣
   Set HeaderRange = xlSheet.Range("A1:C1")
   HeaderRange.MergeCells = true
   xlSheet.Cells(1,1) = "Header"

   '// 設定A1背景色 (15=淺灰色)
   Set MergeHeaderRange = xlSheet.Range("A1")
   MergeHeaderRange.Interior.ColorIndex = 15

   '// 設定第一行為日期格式
   Set AColRange = xlSheet.Range("A:A")
   AColRange.NumberFormatLocal = "yyyy/mm/dd"

   '// 隱藏第四行
   Set DColRange = xlSheet.Range("D:D")
   DColRange.Columns.Hidden = true

   '// 將第一列凍結視窗
   xlSheet.Cells(2,1).Select
   xlApp.ActiveWindow.FreezePanes = true
%>

參考前篇:ASP 操作 Excel 簡單範例(二)

2010年8月26日 星期四

ASP Function Variable

最近 ASP 自訂 Function 的結果不如預期
測了一下, 發現是 Variable 的問題
所以記錄一下

<%
   function BadFunction(a)
      Dim a1
      a1 = a
      a1 = a1 + 1
      BadFunction = a
   end function

   function GoodFunction(a)
      Dim a1
      a1 = a + 1
      GoodFunction = a1
   end function

   Variable_Bad = 2
   Variable_Good = 2
   response.write "Variable_Bad : " & Variable_Bad & "<br>"
   response.write "BadFunction : " & BadFunction(Variable_Bad) & "<br>"
   response.write "Variable_Bad : " & Variable_Bad & "<br>"
   response.write "Variable_Good : " & Variable_Good & "<br>"
   response.write "GoodFunction : " & GoodFunction(Variable_Good) & "<br>"
   response.write "Variable_Good : " & Variable_Good & "<br>"
%>

輸出如下:
Variable_Bad : 2
BadFunction : 3
Variable_Bad : 3                      ---> function 外的變數也被改變了
Variable_Good : 2
GoodFunction : 3
Variable_Good : 2

依結果看來
變數似乎是傳址 (Call by address), 而非傳值 (Call by value)
以致於如果 function 內直接對 input 變數做任何異動時
function 外的變數也會隨之改變

所以最好宣告另一個變數, 儲存 input 變數處理後的結果
不要直接處理 input 變數...

2010年8月3日 星期二

ASP 操作 Excel 簡單範例 (二)

又遇到一些新東東
查得我死去活來
所以在這邊記錄一下

<%
   ' 建立圖表 left:10, top:10, width:640, height:320
   Set MyChart = xlApp.ActiveSheet.ChartObjects.Add(10,10,640,320)

   ' 圖表類型為資料標記折線圖
   MyChart.Chart.ChartType = 65

   ' /* 設定圖表資料來源 */
   ' [參數1]: 資料範圍
   ' [參數2]: 1代表以列取數列 / 2代表以欄取數列
   MyChart.Chart.SetSourceData xlSheet.Range("A1:D10"),2

   ' /* X軸文字以日期格式顯示, 字型大小8 */
   ' [參數]: XlAxisType, 1代表xlCategory(X軸) / 2代表xlValue(Y軸)
   Set XAxes = MyChart.Chart.Axes(1)
   XAxes.TickLabels.NumberFormat = "m/d"
   XAxes.TickLabels.Font.Size = 8

   ' Y軸文字字型大小8
   Set YAxes = MyChart.Chart.Axes(2)
   YAxes.TickLabels.Font.Size = 8

   ' /* 圖示置上, 字型大小8 */
   ' [Position參數]: XlLegendPosition
   MyChart.Chart.Legend.Position = -4160
   MyChart.Chart.Legend.Font.Size = 8

   ' 移除多餘的數列
   MyChart.Chart.SeriesCollection(3).Delete
   MyChart.Chart.SeriesCollection(1).Delete

   ' /* 設定數列顏色 */
   ' 設定數列線條為紅色(ColorIndex=3)
   MyChart.Chart.SeriesCollection(1).Border.ColorIndex=3
   ' 設定數列前景色為黑色(ColorIndex=1)
   MyChart.Chart.SeriesCollection(1).MarkerForegroundColorIndex=1
   ' 設定數列背景色為紅色(ColorIndex=3)
   MyChart.Chart.SeriesCollection(1).MarkerBackgroundColorIndex=3
%>

參考資料:
Chart Type Enumeration : Toolbox.com
XlAxisType Enumeration : MSDN
XlLegendPosition Enumeration : MSDN
ColorIndex : MSDN

參考前篇 : ASP 操作 Excel 簡單範例
參考下篇 : ASP 操作 Excel 簡單範例(三)

2010年7月29日 星期四

ASP FileSystemObject Sample

<%
   Set fs = Server.CreateObject("Scripting.FileSystemObject")

   ' Create new folder
   if fs.FolderExists("C:\Test2") = false then
      fs.CreateFolder "C:\Test2"
   end if

   ' Copy files
   Set SourceFolder = fs.GetFolder("C:\Test1")
   Set SourceFiles = SourceFolder.files
   if SourceFiles.Count > 0 then
      fs.CopyFile "C:\Test1\*.*", "C:\Test2"
   end if
   Set SourceFiles = nothing
   Set SourceFolder = nothing

   ' Show files name
   Set TargetFolder = fs.GetFolder("C:\Test2")
   for each x in TargetFolder.files
      response.write x.Name & "<br>"
   next
   Set TargetFolder = nothing

   ' Delete jpg files
   fs.DeleteFile("C:\Test2\*.jpg")

   Set fs = nothing
%>

參考 W3CSchools

2010年6月1日 星期二

ASP 操作 Excel 簡單範例

.Net , ASP 操作 Excel 的方式都有些不同
所以在這記錄一下

<%
   ' 建立 Excel 應用程式
   Set xlApp=Server.CreateObject("Excel.Application")
   ' 建立 WorkBook
   Set xlBook = xlApp.Workbooks.Add
   ' 建立 WorkSheet
   Set xlSheet = xlBook.Worksheets.Add

   ' 給儲存格值
   xlSheet.Cells(1,1)="A1"
   xlSheet.Cells(1,2)="B1"

   ' 範圍文字變粗體
   xlSheet.Range("A1:B1").Font.Bold = true
   ' 範圍儲存格設框線
   xlSheet.Range(xlSheet.Cells(1,1),
         xlSheet.Cells(1,2)).Borders.Weight = 2
   ' WorkSheet 自動欄寬
   xlSheet.Columns.Autofit()

   ' 存檔
   xlBook.SaveAs "c:\test.xls"
   xlBook.Close
   xlApp.Quit

   Set xlApp = Nothing
   Set xlBook = Nothing
%>

參考下篇 : ASP 操作 Excel 簡單範例 (二)

2010年5月25日 星期二

ASP 頁面編碼造成自動 Refresh

今天遇到一個超怪的問題
我在ASP前面幾行讀取前頁submit過來的資料
將資料更新回DB

發現更新完成的訊息居然會重複alert 2次

查了好久的網路才查到一點眉目
可能是因為頁面編碼(Charset)的問題

我在HTML head中有寫一行
<meta http-equiv="Content-Type" content="text/html; charset=big5">
但其實這行的意義是指
此頁的表單資料要用什麼編碼方式submit出去
並非是指這頁要用什麼編碼方式顯示
詳見保哥寫的一篇[關於各瀏覽器對網頁與文字編碼的處理規則研究整理]

想要設定本頁要用什麼編碼方式顯示
在ASP中,要使用
<%response.charset = "big5"%>
加上這行,我的ASP就一切正常了

個人推測此次的原因為:

一開始沒有設定本頁顯示的編碼
所以一開始預設用utf-8編碼來顯示本頁資料
直到程式開始讀取DB的資料時
發現DB是用big5編碼儲存資料的
所以瀏覽器自動refresh本頁,改變編碼為big5

而更新DB的程式段剛好又在讀取DB資料之前
造成一開始用utf-8編碼顯示頁面時,進行更新,並alert更新完成的訊息
後來遇到程式讀取DB資料,自動refresh本頁後,不會再次更新,但會再alert更新完成的訊息

以此推論 :
因資料與頁面的編碼不符時
僅會refresh client端頁面資料 (並沒有對server再次發出request)
所以ASP程式段不會重複執行
但是client端的javascript全都會重複執行

但我剛好也有另一支程式也是用這種結構寫的
卻沒有這個問題
所以詳細原因還要在釐清...

另外補充一下 :
在 HTML head 中的程式段
好像不會依改變編碼而重新執行
<html>
   <head>
     <script language="javascript">
        alert("Hello World!");
     </script>
   </head>
   <body>

   </body>
</html>

2010年5月21日 星期五

ASP 讀取網站資料夾下檔案

用 ASP 讀取網站資料夾下所有檔案名稱 (包含子資料夾下的檔案)
function  : GetFiles
input 1 : 網站相對路徑
input 2 : 0 (int)
output : 2D Array
             (0, n) : 檔案的 FullName (包含網站相對路徑)
             (1, n) : 檔案的 Name

<%
   dim TemporaryFiles()
   function GetFiles(Path, FileCount)
      set fs = Server.CreateObject("Scripting.FileSystemObject")
      realfilepath = Server.Mappath(Path)
      if fs.FolderExists(realfilepath) = true then
         set folder = fs.GetFolder(realfilepath)
         ' 將目前資料夾下的檔案名稱放入陣列
         for each f in folder.files
            redim preserve TemporaryFiles(2, FileCount+1)
            TemporaryFiles(0, FileCount) = Path & "/" & f.Name
            TemporaryFiles(1, FileCount) = f.Name
            FileCount = FileCount + 1
         next
         ' 繼續找有沒有子資料夾, 有的話, 遞迴掃裡面的檔案和資料夾
         for each subfolder in folder.SubFolders
            call GetFiles(Path & "/" & subfolder.Name, FileCount)
         next
         set folder = nothing
      else
         redim TemporaryFiles(2, 1)
         TemporaryFiles(0, 0) = ""
         TemporaryFiles(1, 0) = "The path is not exist !"
      end if
      set fs = nothing
      GetFiles = TemporaryFiles
   end function
%>

<%
   ' 呼叫 function
   FileArray = GetFiles("UserUpload", 0)
   for i = 0 to ubound(FileArray,2)
      response.write FileArray(0,i) & <br>
      response.write FileArray(1,i) & <br>
   next
%>

2010年5月18日 星期二

正規表達式彙整

順便整理一下 javascript / vbscript (ASP) / C#
三者的正規表達式使用方式

javascript
宣告var RegObj = /pattern/attribute;
屬性i: case-insensitive / g: global / m: multiline matching
比對RegObj.test(target_string);
return true / false
取出
符合文字
var Result = RegObj.exec(target_string);
搭配g, 可以重複使用exec(), 依序取出符合文字
取代
符合文字
target_string.replace(RegObj,replace_string);
return取代後的文字
搭配Global, 可以將所有符合的文字取代
參考 W3CSchools

vbscript (ASP)
宣告Set RegObj = new regexp
RegObj.Pattern = pattern
屬性RegObj.IgnoreCase = true | false
RegObj.Global = true | false
比對RegObj.test(target_string)
return true / false
取出
符合文字
Set Result = RegObj.execute(target_string)
return一個Collection, 以Result(0) 方式讀取
搭配Global, 可以取出所有符合的文字Collection
取代
符合文字
RegObj.replace(target_string,replace_string)
return取代後的文字
搭配Global, 可以將所有符合的文字取代
參考 MSDN

C#
宣告Regex RegObj = new Regex(pattern[,attribute]);
屬性RegexOptions.IgnoreCase / RegexOptions.Multiline ...
比對RegObj.IsMatch(target_string);
return true / false
取代
符合文字
RegObj.Replace(target_string,replace_string);
return取代後的文字
參考 MSDN, mikesdotnetting

ASP 正規表達式

前面寫了篇 Javascript 正規表達式
這邊當然也要補上一篇 ASP 正規表達式的用法

範例 :
<%
   Pwd = "9901"

   Set RegPwd = new regexp
   RegPwd.Pattern = "^\d{6,8}$"
   RegPwd.IgnoreCase = true  '// 忽視大小寫
  
   if RegPwd.Test(Pwd)=false then
      response.write "Password is error !" & "<br>"
   else
      response.write "Welcome !" & "<br>"
   end if
  
   TestStr = "Welcome 16547 to the show!"
  
   Set RegStr = new regexp
   RegStr.Pattern = "\d"
  
   RegStr.Global = true
   '//true:整個字串進行比對, false:只找出符合的第一個   
   '//Default 為false
  
   Set MatchObj = RegStr.Execute(TestStr)
   For each obj in MatchObj
      response.write obj & "<br>"
   Next
  
   response.write RegStr.Replace(TestStr,"") & "<br>"
  
%>

ASP 動態增加陣列長度

前面寫了篇 Javascript 動態增加陣列長度
這邊順便記錄一下 ASP 動態陣列的使用方式

一般 vbscript 宣告陣列是 dim Arr(10)
要使用動態陣列有 2個步驟

1. dim Arr()  <-- 這邊不要給陣列長度
2. redim [preserve] Arr(a)  <-- 利用 redim 重新定義陣列長度

ps.1 原先用 dim Arr(f) 方式宣告陣列, f 必須為常數, 也就是 1,2,3,...
  而 redim Arr(a) 方式宣告陣列, a 可以是變數, a = 5, redim Arr(a)

ps.2 preserve 是 option, 代表是否要保留原本陣列中的資料
  如果是多維陣列, 設了 preserve 後, 只能變動最後一維的長度
  (如果 redim 後的陣列長度小於原先長度, 超出長度的資料會消失)

範例 :
<%
   dim MyArray()
   for i=1 to 9
      redim preserve MyArray(i)
      MyArray(i-1) = i*5
   next
   ' 陣列最後長度是10 (0~9)
   ' 所存資料有9個, 依序為5,10,15,...,45
%>