Ajax Hack 之hack 12不重新整理瀏覽器的情況下向伺服器提交text或textarea的值

來源:互聯網
上載者:User
ajax|伺服器|瀏覽器|重新整理 Ajax Hack 之hack 12不重新整理瀏覽器的情況下向伺服器提交text或textarea的值

本節主要講的是:將text或textarea的值平滑地傳遞給伺服器。

當使用者輸入text或textarea的值以後,Ajax能將這些值自動的發給伺服器。程式等待text的onblur

事件,然後使用request對象向伺服器發送資料。在常用的情況是,使用者點擊一個按鈕,然後將

整個form作為一個大的資料包向伺服器發送。伺服器相應也與此類似。例如,線上測試或者

教程能在使用者輸入完成以後很快顯示結果,而不需要使用者點擊按鈕重新整理頁面得到結果。

形如form的某些元素,如text等失去鍵盤焦點的時候將激發onblur事件,通常是使用者點擊tab鍵

或者點擊其他地區。也可以使用onkeypress, onkeydown, 或 onkeyup 等來處理使用者和text組件

的互動。

接下來向伺服器發送資料的步驟:

1. 使用者將焦點移入text。

2. 在text中輸入資訊。

3. 使用者點擊tab鍵或點其他地區。

使用者在text裡輸入一些資訊,然後程式自動將資訊發給伺服器。在這個過程中,最好加入

資訊提示,如alert一個對話方塊,在發送過程中最好能讓使用者知道程式在運作,如有一個進度條。

下面是頁面的html代碼:

“http://www.w3.org/TR/2000/REC-xhtml1–20000126/DTD/xhtml1-strict.dtd”>

Get stats from textareas and textfields using Ajax

javascript:void%200>Enter a few words for submitting to our server:



Enter a phrase for submitting to our

server: <br/><br />

使用者不必點擊任何按鈕來發送資訊,每個text都能控制自己的行動。

當使用者按tab鍵,或者點了text組件以外的地區時,onblur事件將激發處理常式。下面的代碼

將顯示事件處理者是如何進行工作的。

本節使用的js原始碼在檔案hacks_2_1.js中。這個檔案中有程式運行所需的所有代碼。

代碼中包括了發送請求和處理相應值(handleResponse( )函數)的所有代碼。在下一節中,

會講述如何將伺服器相應插入到text組件中的相關技術,但這絲毫不影響你理解handleResponse( )

函數,下面是js代碼:

var formObj = null;

var formObjTyp = “”;

var request=null;

//input field’s event handlers

window.onload=function( ){

var txtA = document.getElementById(“tarea”;

if(txtA != null){

txtA.onblur=function( ){if (this.value) { getInfo(this);}}; }

var tfd = document.getElementById("tfield");

if(tfd != null){

tfd.onblur=function( ){if (this.value) { getInfo(this);}}; }

}

function getInfo(obj){

if (obj == null ) { return; }

formObj=obj;

formObjTyp =obj.tagName;

if(formObjTyp "input" || formObjTyp "INPUT"){

formObjTyp = formObjTyp " "formObj.type;

}

formObjTyp = formObjTyp.toLowerCase( );

var url = “http://www.parkerriver.com/s/webforms?objtype=”+

encodeURIComponent(formObjTyp)+“&val=”+ encodeURIComponent(obj.value);

httpRequest(“GET”,url,true);

}

//event handler for XMLHttpRequest

function handleResponse( ){

try{

if(request.readyState == 4){

if(request.status == 200){

var resp = request.responseText;

var func = new Function(“return ”+resp);

var objt = func( );

if(formObjTyp == “textarea”{

if(formObj != null){

formObj.value = objt.Form_field_type +

“ character count: ”+objt.Text_length+

“\\nWord count: ”+

objt.Word_count+“\\nServer inf ”+

objt.Server_info;

}

} else if(formObjTyp == “input text”{

if(formObj != null){

formObj.value = objt.Form_field_type +

“ # characters: ”+objt.Text_length+

“ Word count: ”+objt.Word_count; }

}

} else {

//request.status is 503

//if the application isn‘t available;

//500 if the application has a bug

alert(

“A problem occurred with communicating between the ”+

“XMLHttpRequest object and the server program.”;

}

}//end outer if

} catch (err) {

alert(“It does not appear that the server is available ”+

“for this application. Please”+

“ try again very soon. \\nError: ”+err.message);

}

}

/* Initialize a request object that is already constructed */

function initReq(reqType,url,bool){

try{

/* Specify the function that will handle the

HTTP response */

request.onreadystatechange=handleResponse;

request.open(reqType,url,bool);

request.send(null);

} catch (errv) {

alert(

“The application cannot contact the server ”+

“at the moment. ”+

“Please try again in a few seconds.” );

}

}

/* Wrapper function for constructing a request object.

Parameters:

reqType: The HTTP request type, such as GET or POST.

url: The URL of the server program.

asynch: Whether to send the request asynchronously or not. */

function httpRequest(reqType,url,asynch){

//Mozilla-based browsers

if(window.XMLHttpRequest){

request = new XMLHttpRequest( );

} else if (window.ActiveXObject){

request=new ActiveXObject(“Msxml2.XMLHTTP”;

if (! request){

request=new ActiveXObject(“Microsoft.XMLHTTP”;

}

}

//the request could still be null if neither ActiveXObject

//initialization succeeded

if(request){

initReq(reqType,url,asynch);

} else {

alert(“Your browser does not permit the use of all ”+

“of this application‘s features!”;}

}

代碼首先聲明了兩個全域的js變數:formObj和formObjTyp。前者持有input

或textarea對象(其他函數需要訪問),後者持有一個string描述form對象的標記

名稱,如input或textarea。這個string也是伺服器組件需要的變數之一。

如前所述,在瀏覽器載入頁面時,代碼就為text組件的onblur事件指定了處理器。

你可以使用js在window的onload事件處理中來完成這個工作。使用window.onload,

也可在html中直接指定。

window.onload=function( ){

var txtA = document.getElementById(“tarea”;

if(txtA != null){

txtA.onblur=function( ){if (this.value) { getInfo(this);}}; }

var tfd = document.getElementById(“tfield”;

if(tfd != null){

tfd.onblur=function( ){if (this.value) { getInfo(this);}}; }

}

現在,這些text是hot的。當使用者輸入完資訊,退出控制以後,資訊輸入就完成了,

接下來向伺服器發送資訊;使用者不必點擊其他按鈕。

text-field事件處理器調用getInfo( )函數。函數抽取使用者鍵入的資訊,並向伺服器發送。

function getInfo(obj){

if (obj == null ) { return; }

formObj=obj;

formObjTyp =obj.tagName;

if(formObjTyp "input" || formObjTyp "INPUT"){

formObjTyp = formObjTyp " "formObj.type;

}

formObjTyp = formObjTyp.toLowerCase( );

var url = “http://www.parkerriver.com/s/webforms?objtype=”+

encodeURIComponent(formObjTyp)+“&val=”+

encodeURIComponent(obj.value);

httpRequest(“GET”,url,true);

}

getInfo( )函數的參數是text或textarea對象。傳遞進取是為了能夠取得該對象的資訊。

最後一部分httpRequest("GET",url,true)函數發送使用者資訊到伺服器。

然而,在代碼調用函數前,一些事情發生了。伺服器組建期待的是一個描述form類型的字串。

formObjTyp =obj.tagName;

if(formObjTyp "input" || formObjTyp "INPUT"){

formObjTyp = formObjTyp " "formObj.type;

}

formObjTyp = formObjTyp.toLowerCase( );

var url = “http://www.parkerriver.com/s/webforms?objtype=”+

encodeURIComponent(formObjTyp)+“&val=”+ encodeURIComponent(val);

httpRequest(“GET”,url,true);

全域函數encodeURIComponent( )方法用來確認某些特性,如空格等,在他們被包含到URL中

的時候得到編碼。否則,程式可能會發送一個錯誤的URL給伺服器,而引發錯誤。

接下來:

在提交資料以後,會發生什麼呢? 這要取決於你的程式。下一節將講述另一個話題:是用js和

ajax將伺服器相應值插入到一個存在的text組件中。

<

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.