Ajax入门

初学Ajax,写了一个最简单例子,开始学习之旅。使用的是Asp.net + ajax方式
先构建HTML 和 Javascript代码

<script type="text/javascript">

    		var xmlHttp;

    		function ajaxFunc(url, cfunc) {

    		    if (window.XMLHttpRequest) {        //firefox、chrome、....
    		        xmlHttp = new XMLHttpRequest();
    		    } else {//IE6以下
    		        xmlHttp = new ActiveXObject();
    		    }

    		    xmlHttp.open("Get", url, true);     //请求方式、地址、异步
    		    xmlHttp.send();
    		    xmlHttp.onreadystatechange = cfunc;//回调函数
    		}

    		function load() {
    		    var message = document.getElementById("message").value;

    		    var url = "http://localhost:6118/Store/Browse?m=" + message;    //Get方式,传值

    		    ajaxFunc(url, function () {
    		        //响应完成,xmlHttp.status==0本地响应成功,我是使用本地服务器
    		        if (xmlHttp.readyState == 4 && (xmlHttp.status == 0 || xmlHttp.status == 200)) {
    		            document.getElementById("myDiv").innerHTML = xmlHttp.responseText;
    		        }
    		    });
    		}
			
</script>


<input type="text" id="message" />
<input type="button" onclick="load()"  value="Ajax请求"/>
<div id="myDiv"></div>

 .cs后台代码

 public class StoreController : Controller
 {

        public string Browse(string m)
        {
            string message ="你输入的是:"+ m;

            return message;
        }
}

 好啦,这样就完成了,注意的是,Ajax不能跨域访问,不然xmlHttp.responseText为“” ,以后谈跨域解决方法。

好吧,效果这样!

posted @ 2012-07-21 12:12  Mr.Lin_♪  阅读(133)  评论(0)    收藏  举报