前后端分离(一)

一、基础知识

1、Ajax是Asynchronous JavaScript and XML 的缩写,即异步的JavaScript和XML。传统的网页(不使用Ajax)如果需要更新内容,必须重载整个网页。Ajax是一种无需重新加载整个网页的情况下,能够更新部分网页的技术。

2、一般处理程序:ASP.NET网站中这种扩展名为ashx的程序称为"一般处理程序",它与普通的扩展名为aspx的窗体网页程序不同的是没有HTML的窗体网页代码,适合作为后台服务器处理数据。

二、Ajax-DEMO

client.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Ajax</title>
    <script language="javascript">
	var http=null;
    function getHttp() {
        //获取XMLHttpRequest对象
        var http = null;
        try {
            if (window.ActiveXObject)
                http = new ActiveXObject("Microsoft.XMLHTTP");
            else if (window.XMLHttpRequest)
                http = new XMLHttpRequest();
            else
                alert('Getting XMLHttpRequest faild');
        }
        catch (exp) {
            alert(exp.description);
        }
        return http;
    }
	
	function process()
	{
		if(http.readyState==4)
		{
			//获取服务器响应,显示结果
            document.getElementById("msg").innerHTML = http.responseText;
		}
	}

    function getDateTime(){
        try {
            //获取XMLHttpRequest对象
			if(http==null)
			{
				http = getHttp();
			}
			
			http.onreadystatechange=process;
			
			//发送数据
            http.open("GET", "server.ashx?&rnd="+Math.random().toString(), true);
			http.send(null);
            
        }
        catch (exp) {
            alert(exp.description);
        }
    }
    </script>

</head>
<body>
	<img src="image.jpg" eidth="50" height="50"/>
	<input type="button" value="获取" onclick="getDateTime()" />
	<span id="msg" />
</body>
</html>

1、加载同目录下的一张图片

2、每次点击“获取”按钮会像服务器端发送异步请求


server.ashx

<%@ WebHandler Language="C#" Class="DEMO.server" Debug="true"%>
using System;
using System.Web;
using System.Threading;

namespace DEMO
{
	public class server : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
	    String s = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
	    Thread.Sleep(1000);
	    //输出结果
            context.Response.Clear();
            context.Response.ContentType = "text/plain";
            context.Response.Write(s);
            context.Response.Flush();
        }

       
    }
}


当有请求来的时候、获取当前时间然后传回客户端(更复杂的功能可以以此为基础进行扩展)

Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <globalization requestEncoding="gb2312" responseEncoding="gb2312"/>
  </system.web>
</configuration>


原文地址:https://www.cnblogs.com/haxianhe/p/9271211.html