ASP.NET MVC2中三种ajax实现方式-原始JavaScript

来源:互联网 发布:运营美工推广招聘 编辑:程序博客网 时间:2024/05/16 03:10

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h4>Comments</h4>   
    <ul id="comments">       
    </ul>
        <%= Html.TextArea("Comment", new{rows=5, cols=50}) %>
        <button type="submit" onclick="getMessage()">Add Comment</button>
             <span id="indicator" style="display:none"><img src="../../content/load.gif" alt="loading..." /></span>                                

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="headContent" runat="server">
    <script  type="text/javascript">

 function getXmlHttpRequest() {
            var xhr;
            //check for IE implementation(s)
            if (typeof ActiveXObject != 'undefined') {
                try {
                    xhr = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }
            } else if (XMLHttpRequest) {
                //this works for Firefox, Safari, Opera 
                xhr = new XMLHttpRequest();
            } else {
                alert("对不起,你的浏览器不支持ajax");
            }

            return xhr;
        }
   
        function getMessage() {
            //get our xml http request object
            var xhr = getXmlHttpRequest();
 
            //prepare the request
            xhr.open("GET", "Comment/AddCommentServer?comment=" + document.getElementById("Comment").value, true)
           
            //setup the callback function
            xhr.onreadystatechange = function() {
             //readyState 4 means we're done
             if(xhr.readyState != 4) return;
     
             //populate the page with the result
             document.getElementById('comments').innerHTML = document.getElementById('comments').innerHTML + xhr.responseText;
            };
  
            //fire our request
            xhr.send(null);
        }

    </script>
</asp:Content>

原创粉丝点击