ajax,training my javascript!手寫AJAX,用POST方法傳值

普通的一個HTML~~~

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
        <title>無標題頁</title>
        <script language="javascript" type="text/javascript">
        var httpXML;
        function createXMLObject()
        {
                if (window.ActiveXObject)
                {
                        httpXML=new ActiveXObject("Microsoft.XMLHTTP");
                        
                }
                else if(window.XMLHttpRequest)
                {
                        httpXML=new XMLHttpRequest();
                }

        }
        
        function startRequest()
        {
                createXMLObject();
                var query="yourname="+ document.getElementById("txtname").value;
                
                httpXML.onreadystatechange=handleEventStateChange;
                httpXML.open("POST","postData.aspx",true);
                httpXML.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")//這一句是關鍵,經過試驗,這一句需要放在open後……
                
                httpXML.send(query);
        }
        
        function handleEventStateChange()
        {
                if (httpXML.readyState==4)
                {
                        if (httpXML.status==200)
                        {
                                //dosomething
                                alert(httpXML.responseText);
                        }

                }

        }
</script>
</head>
<body>
         <input type="text" id="txtname" value="111" onblur="startRequest();" />
</body>
</html>


postData.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="postData.aspx.cs" Inherits="postData" %>



postData.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class postData : System.Web.UI.Page
{
        protected void Page_Load(object sender, EventArgs e)
        {

                string requestquery = Request["yourname"].ToString();
//string requestquery=Request.Form["yourname"].ToString();
                Response.Write("Welcome " + requestquery);

        }
}



httpXML.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")//這一句是關鍵,經過試驗,這一句需要放在open後……
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章