1. 程式人生 > >(搬家到)fys-summer.blog.163.com

(搬家到)fys-summer.blog.163.com

一個考試系統的部分程式碼,功能是非同步提交答案!

曾經遇到的問題:1.非同步提交,2.IE不支援中文,3.提交的資料量過多丟失,本文已經解決了三個這樣的問題

var http_request = false;
	var promptid = false;
       function save(examPaperidDetailID,answerid,promptid_,submitButtonFlag,scoreid){
		document.getElementById(promptid_).innerHTML = '儲存中......';   //提示
		promptid = promptid_;
		var score = 0;
		if (document.getElementById(scoreid) != null){
			score = document.getElementById(scoreid).value
		}
		var factory = new XMLHttpRequestFactory();
		http_request = factory.getHttpRequest3();
		if (!http_request) {
			alert('建議使用IE或Firefox瀏覽器!');
		} else {
			var linkurl = "/subsystem/talent/exampaper/SaveAnswerAjax.jsp" 
			var param = "id=" + Math.random()
					+ "&examPaperidDetailID=" + examPaperidDetailID
					+ "&answer=" + escape(document.getElementById(answerid).value)
					+ "&submitButtonFlag="+submitButtonFlag
					+ "&score="+escape(score);
			//alert(param);
                       //將中文 放到  escape('中文') 否則IE提交的時候會丟失資料
                       // "id=" + Math.random() 這樣子是為了每次都可以更新一下請求方式
			http_request.open("POST", linkurl, true);  // 利用POST 和 非同步

                       // 下面這兩句 比較重要,缺少會導致提交的資料為空
			http_request.setRequestHeader("content-length",param.length);  //post提交設定項
    		        http_request.setRequestHeader("content-type","application/x-www-form-urlencoded");  //post提交設定項
			
                       http_request.onreadystatechange = callback;
			http_request.send(param); // 引數在這裡傳進來 
		}
	}

    function callback() {
      if (http_request.readyState == 4 && http_request.status == 200) { 
      		 if(document.getElementById(promptid) != null){
            	 document.getElementById(promptid).innerHTML = http_request.responseText; //返回提示資訊
             }
         } 
    }