Home >Backend Development >C#.Net Tutorial >Detailed case summary of learning .net and ajax

Detailed case summary of learning .net and ajax

高洛峰
高洛峰Original
2016-12-16 16:32:411071browse

First understand what ajax is.

AJAX is not a new programming language, but a technology for creating better, faster and more interactive web applications.
With AJAX, your JavaScript can communicate directly with the server using JavaScript's XMLHttpRequest object. Through this object, your JavaScript can exchange data with the web server without reloading the page.
AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, which allows a web page to request a small amount of information from the server instead of the entire page.

When it comes to javascript, everyone will think of browser compatibility issues. In fact, ajax also needs to consider this issue. Because the web javascript classes used by different browsers are different, the effects produced will not be the same. No more nonsense below, just introduce the code directly for your reference.
  {
    var xmlhttp;//Non-IE browser creates XmlHttpRequest object
   if(window.                                                                                                                                                                                                        // IE browser creates
                  try {
                                                                                  try {
                                                                                                                                                     }
                                                                                          // xmlhttp.open("POST", "GetDate.ashx?nd=" + new Date( ), false); //Send a request to a page on the server
                                         {
              xxxxx = xmlhttp.responseText;//Here Here we can return the parameters we passed to our html tags, or other variable processing issues
                                                                                                                                                                                       //responseText                                                                                    
}
                                                                                                                                                                                               It depends, so I don’t need to introduce it here.

How do you feel when you see these codes? For students who have just learned javascript or ajax, it is really difficult to remember these codes. How do you understand these things? I basically have comments above. Everyone can generally understand it. But if each page needs to be partially refreshed, it will feel like it is very troublesome to write such code for each page. jQuery has helped us complete a lot of things, which can reduce the difficulty of developing our projects. The following is the use jQuery code:

$.ajax({

type: "POST",

url: "some.php",

data: "name=John&location=Boston",
success: function(msg){
alert( " Data Saved: " + msg );
}
});Another way

$.post("test.php", { name: "John", time: "2pm" },
function(data){

alert("Data Loaded: " + data);

}); Isn't it very simple? Here we are calling the function he wrote, and we can implement our no-refresh code. Now it feels like it is useless. Isn’t it very simple to refresh the page, but we are just passing small data. It will be very troublesome to extract data from the database. Here is part of my code to let everyone think about it

The following is my implementation of no refresh Comment and display front-end and back-end code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxComment.aspx.cs" Inherits="ajax learning.No refresh comment.AjaxComment1" %>



   
   
   


   


   

                    DeleteMethod="Delete" InsertMethod="Insert"
            OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
            TypeName="ajax学习.DataSetCommentTableAdapters.T_CommentTableAdapter"
            UpdateMethod="Update">
           
               
           

           
               
               
               
           

           
               
               
               
               
           

       

       

           
               
                   
  • 评论日期:<%#Eval("PostDate")%>,IP:<%#Eval("IP")%>,内容:<%#Eval("Msg")%>

  •            

           

           

   

    value="提交" />
   



Backend code (AjaxComment.ashx)

using System;
using System.Collections.Generic;
using System.Linq;
using System .Web;
using ajax learning.DataSetCommentTableAdapters;
using System.Web.Services;
namespace ajax learning.No refresh comments
{
///


/// Summary description of AjaxComment
/// < /summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class AjaxComment: IHttpHandler
{

public void ProcessRequest(Http Context context)
{
                                                                                                                            { ;
                              return false; Is there something wrong with the front-end code? What should I do if I pass data with many fields and attributes? If every data is split()ed like this, it will definitely be tiring if I do a big project. Below, jQuery has done a good thing for us, which is the use of json. Below I introduce my json code for using non-refresh comments

front-end code:




   
   
   


   


       


    后台代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using ajax学习.DataSetCommentTableAdapters;
    using System.Web.Script.Serialization;
    namespace ajax学习.无刷新分页
    {
        ///


        /// PagedServices 的摘要说明
        ///

        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        public class PagedServices : IHttpHandler
        {

            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                 // context.Response.Write("Hello World");
                string action=context.Request["action"];
                var adapter = new T_CommentTableAdapter();
                if (action == "getpagecount")
                {
                   
                    int count=adapter.SelectCount().Value;
                    int pagecount=count/10;
                    if(count%10!=0)
                    {
                        pagecount++;
                    }
                    context.Response.Write(pagecount);
                }
                else if(action=="getpagedata")
                {
                    string pagenum=context.Request["pagenum"];
                    int iPageNum = Convert.ToInt32(pagenum);
                    var data = adapter.GetPagedData((iPageNum - 1) * 10 + 1, iPageNum * 10);
                    List list=new List ();
                    foreach(var row in data)
                    {
                        list.Add(new Comments() { Id = (int)row.Id, IP = row.IP, Msg = row.Msg, PostDate = row.PostDate, });
                    }
                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    context.Response.Write(jss.Serialize(list));
                } 
            }

            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }

        public class Comments
        {
            public int Id { get; set; }
            public string IP{get;set;}
            public string Msg{get;set;}
            public string PostDate{get;set;}
        }
    }这样我们真的是省了很多力气啊,是不是jQuery很强大啊。。。。。。。。。。。。。

    然后吧,微软感觉我必须封装自己的ajax,这样使得开发者做项目变得容易一些,微软真的是帮我们封装好了一个,但是对于高手来说,大家都不想用,感觉这样的代码太呆板,一点不灵活,我再下面引入代码,供新手参考:(不了解ajax运行原理的新手一样可以使用ajax快速开发新的项目)

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UpdatPanel.aspx.cs" Inherits="ajax学习.UpdatePanel.UpdatPanel" %>

    <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>



       


       


       
       

       

           
            onclick="Button1_Click" />
       

       
      
           
               
                    Text="Ajax无刷新显示当前时间" />
                   

               

           

       

       


    但是微软后来真的是开发一个很好地工具,那就是ajax与WCF的结合,废话少说,引入代码,供大家思考

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WCF_Ajax.aspx.cs" Inherits="ajax学习.WCF之Ajax.WCF_Ajax" %>



       
       
       


       


       

       
           
               
                    //注意路径处理问题,
               

           

           
           
           

       
       



    Backend code: (PersonService.svc)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System. Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Web;
    using System.Text;

    namespace ajax learning.WCF’s Ajax
    {
                                                                                                                                           ")]
     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
     public class PersonService
     {
                                                                                                                                                                          ​(The default ResponseFormat is WebMessageFormat.Json)
                                                                                                                                                                                                                                       ​WebOperationContext .Current.outgoingResponse.ContentType = "Text/XML"; Ontract] u Public Person Getperson (int id)
                                                                                                                                            . {
                    public string Name { get; set; }                                             use using using .net using . Chinese website!



    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn