ASP.NET学习笔记(5)——原生Ajax基本操作

说明(2017-11-4 15:32:49):

1. 回北京后又快一个月了,上次在家写的下回预告,到底是没把加水印写完,而且这次也不想写。。

2. 上次许的愿,十月份看完asp.net,已经泡汤了,翻了一下,一共十天的课程,我搞不好大半年就看了6天的。。

3. 总而言之,这次的笔记是用JavaScript的原生ajax操作,应该只是了解写法吧,因为下一讲就是jQuery封装好的ajax操作了。

Ajax_Get.aspx:

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Ajax_Get.aspx.cs" Inherits="_06_Ajax.ajax" %>

 <!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input type="button" name="name" value="显示用户" id="btnShow" />
</form>
</body>
<script type="text/javascript">
var btnShow = document.getElementById("btnShow");
btnShow.onclick = function () {
var xhr;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//open里面放用户名和密码传值
xhr.open("get", "Ajax.ashx?userName=zhangsan&passWord=123", true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == && xhr.status == ) {
alert(xhr.responseText);
}
};
};
</script>
</html>

Ajax_Post.aspx:

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Ajax_Post.aspx.cs" Inherits="_06_Ajax.Ajax_Post1" %>

 <!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input type="button" name="name" value="显示用户" id="btnShow" />
</form>
</body>
<script type="text/javascript">
var btnShow = document.getElementById("btnShow");
btnShow.onclick = function () {
var xhr;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("post", "Ajax.ashx", true);
//手动加head头,第一次没成功,因为x前面的斜杠写成横杠了
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//send里放传的值
xhr.send("userName=lisi&passWord=456");
xhr.onreadystatechange = function () {
if (xhr.readyState == && xhr.status == ) {
alert(xhr.responseText);
}
};
}; </script>
</html>

Ajax.ashx:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace _06_Ajax
{
/// <summary>
/// ajax1 的摘要说明
/// </summary>
public class ajax1 : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//string method = context.Request.HttpMethod();判断请求方式,get还是post
//get和post都发送到这个ashx页面,反正都是接受用户名和密码
string userName = context.Request["userName"];
string passWord = context.Request["passWord"];
context.Response.Write(userName + passWord);
} public bool IsReusable
{
get
{
return false;
}
}
}
}
上一篇:linux开机自启动服务优化设置命令


下一篇:MongoDB学习笔记(2):数据库操作及CURD初步