XMLHttpRequest对象创建

所有现代浏览器均支持XMLHttpRequest对象( IE5 和 IE6 使用 ActiveXObject)。

XMLHttpRequest用于在后台与服务器交换数据。这意味着可以再不重新加载整个网页的情况下,对网页的某部分进行更新。

XMLHttpRequest对象请求后台

open(mehod,url,async);

规定请求的类型,URL以及是否异步处理请求。

mehod:请求类型;GET或者POST;

url:文件在服务器上的位置。

async:true(异步)或false(同步)

 <%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function loadName(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP ");
}
xmlHttp.open("get","getAjaxName?name=jack&age=18",true);
xmlHttp.send();
}
</script>
<body>
<div style="text-align: center">
<div>
<input type="button" value="Ajax获取数据" onclick="loadName()"/>
&nbsp;&nbsp;<input type="text" id="name" name="name"/></input>
</div>
</div>
</body>
</html>

send(string)将请求发送到服务器。

string:仅用于POST请求

GET还是POST?

与POST相比,GET更加简单也更快,并且在大部分情况下都能使用。

然而,在以下情况下,请使用POST请求:

无法使用缓存文件(更新服务器的文件或者数据库);

向服务器发送大量数据(POST没有数据量限制);

发送包含未知字符的用户输入时,POST比GET更稳定也更可靠;

setRequestHeader(head,value)

详情求添加HTTP头。

header:规定头名称

value:规定头的值。

xmlhttp:setRequestHeader("content-type","application/x-www-form-urlencoded");

异步 -True或False ?

AJAX指的是异步 javaScript和XML(Asynchronous javaScript and XML).

为True的话,表示的是异步,异步表示的程序请求服务器的同时,程序可以继续执行;能提高系统的运行效率;

为False的话,表示同步,JavaScript会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会挂起或停止。

我们一般都是用True;

 <%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function loadName(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP ");
}
xmlHttp.open("post","getAjaxName",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("name=jack1&age=19");
}
</script>
<body>
<div style="text-align: center">
<div>
<input type="button" value="Ajax获取数据" onclick="loadName()"/>
&nbsp;&nbsp;<input type="text" id="name" name="name"/></input>
</div>
</div>
</body>
</html>

XMLHttpRequest对象响应服务器

onreadystatechange事件

当请求被发送到服务器时,我们需要执行一些基于响应的任务。

每当readyState改变时,就会触发 onreadystatechange事件。

readyState属性存有XML  HttpRequest的状态信息。

下面是 XMLRequest对象的三个重要的属性:

onreadystatechange存储函数(或函数名),每当readyState属性改变时,就会调用该函数。

readState

存有XMLHttpRequest的状态,从0到4发生变化:

0:请求为初始化

1:服务器连接已建立

2:请求已接收

3:请求处理中

4:请求已完成,且响应已就绪

status:

200:“OK”

404:未找到页面

在 onreadystatechange时间中,我们规定当服务器响应已做好被处理的准备所执行的任务。

如需获取来自服务器的响应,请使用XMLHttpRequest对象的response或responseXML属性

属性  描述

responseText获得字符串形式的响应数据。

responseXML获得XML形式的相应数据。(了解即可)

Json格式语法

 JSON 对象
{“name”:"张三","age":22}
JSON 数组
{
“student”:[
{"name":"张三","age":22},
{“name”:"李四","age":23},
{"name":"王五",“age”:24}
]
}
JSON嵌套
{
“student”:[
{"name":"张三","age":22,"score":{"chinese":90,"math":100,"english":80}},
{“name”:"李四","age":23,"score":{"chinese":80,"math":89,"english":85}},
{"name":"王五",“age”:24,"score":{"chinese":75,"math":123,"english":70}}
]
}

把Json串换成Json对象

var dataobj=eval("("+data+")");//转换为json对象

引入Json.lib包!

 ajax.jsp

 <%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function loadInfo(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP ");
}
alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
xmlHttp.onreadystatechange=function(){
alert("readState状态"+xmlHttp.readyState+";status状态"+xmlHttp.status);
if(xmlHttp.readyState==4&&xmlHttp.status==200){
alert(xmlHttp.responseText);
var dataobj=eval("("+xmlHttp.responseText+")");
alert("name="+dataobj.name);
alert("age="+dataobj.age);
document.getElementById("name").value=dataobj.name;
document.getElementById("age").value=dataobj.age;
}
};
xmlHttp.open("get","getAjaxInfo",true);
xmlHttp.send();
}
</script>
<body>
<div style="text-align: center">
<div>
<input type="button" value="Ajax获取信息" onclick="loadInfo()"/>
&nbsp;&nbsp;姓名:<input type="text" id="name" name="name"/>
&nbsp;&nbsp;年龄:<input type="text" id="age" name="age"/>
</div>
</div>
</body>

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>HeadFirstAjaxJson</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>getAjaxInfoServlet</servlet-name>
<servlet-class>com.java1234.web.GetAjaxInfoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getAjaxInfoServlet</servlet-name>
<url-pattern>/getAjaxInfo</url-pattern>
</servlet-mapping>
</web-app>

GetajaxInfoServlet 1 package com.java1234.web;


import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class GetAjaxInfoServlet extends HttpServlet{ /**
*
*/
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/Html;charset=utf-8");
PrintWriter out=response.getWriter();
String ResultJson="{\"name\":\"张三\",\"age\":22}";
        或者这样写:

JSONObject ResultJson=new JSONObject();
                ResultJson.put("name","张三");
          ResultJson.put("age", 21);

0         out.println(ResultJson);
         out.flush();
out.close();
}
}

 研究数组嵌套:

 package com.java1234.web;

 import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; public class GetAjaxInfoServlet extends HttpServlet{ /**
*
*/
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String action=request.getParameter("action");
if("resultJson".equals(action)){
doGetResultJson(request,response);
}else if("JsonArray".equals(action)){
doGetJsonArray(request,response);
}
}
private void doGetResultJson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/Html;charset=utf-8");
PrintWriter out=response.getWriter();
//String ResultJson="{\"name\":\"张三\",\"age\":22}";
JSONObject ResultJson=new JSONObject();
ResultJson.put("name","张三");
ResultJson.put("age", 21);
out.println(ResultJson);
out.flush();
out.close();
}
private void doGetJsonArray(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/Html;charset=utf-8");
PrintWriter out=response.getWriter();
/*{
5 “student”:[
6 {"name":"张三","age":22},
7 {“name”:"李四","age":23},
8 {"name":"王五",“age”:24}
9 ]
10 } *{
“student”:[
{"name":"张三","age":22,"score":{"chinese":90,"math":100,"english":80}},
{“name”:"李四","age":23,"score":{"chinese":80,"math":89,"english":85}},
{"name":"王五",“age”:24,"score":{"chinese":75,"math":123,"english":70}}
]
}
*
*
*
*
*/ JSONObject ResultJson=new JSONObject();
JSONArray JsonArrays=new JSONArray(); JSONObject jsonScore1=new JSONObject();
jsonScore1.put("chinese", 90);
jsonScore1.put("math", 100);
jsonScore1.put("english", 80);
JSONObject jsonScore2=new JSONObject();
jsonScore2.put("chinese", 80);
jsonScore2.put("math", 100);
jsonScore2.put("english", 50);
JSONObject jsonScore3=new JSONObject();
jsonScore3.put("chinese", 99);
jsonScore3.put("math", 102);
jsonScore3.put("english", 100);
JSONObject ResultJson1=new JSONObject();
ResultJson1.put("name", "张三");
ResultJson1.put("age", 22);
ResultJson1.put("score", jsonScore1);
JSONObject ResultJson2=new JSONObject();
ResultJson2.put("name", "李四");
ResultJson2.put("age",23);
ResultJson2.put("score", jsonScore2);
JSONObject ResultJson3=new JSONObject();
ResultJson3.put("name", "王五");
ResultJson3.put("age", 25);
ResultJson3.put("score", jsonScore3); JsonArrays.add(ResultJson1);
JsonArrays.add(ResultJson2);
JsonArrays.add(ResultJson3);
ResultJson.put("students", JsonArrays);
out.println(ResultJson);
out.flush();
out.close();
}
}

jsp:

 <%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function loadInfo(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP ");
}
alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
xmlHttp.onreadystatechange=function(){
alert("readState状态"+xmlHttp.readyState+";status状态"+xmlHttp.status);
if(xmlHttp.readyState==4&&xmlHttp.status==200){
alert(xmlHttp.responseText);
var dataobj=eval("("+xmlHttp.responseText+")");
alert("name="+dataobj.name);
alert("age="+dataobj.age);
document.getElementById("name").value=dataobj.name;
document.getElementById("age").value=dataobj.age;
}
};
xmlHttp.open("get","getAjaxInfo?action=resultJson",true);
xmlHttp.send();
} function loadInfo2(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP ");
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4&&xmlHttp.status==200){
alert(xmlHttp.responseText);
var dataobj=eval("("+xmlHttp.responseText+")");
var st=document.getElementById("studentTable");
var newTr;//行
var newTd0;//第一列
var newTd1;//第二列
var newTd2;//第二列
for(var i=0;i<dataobj.students.length;i++){
var student=dataobj.students[i];
newTr=st.insertRow();
newTd0=newTr.insertCell();
newTd1=newTr.insertCell();
newTd2=newTr.insertCell();
newTd0.innerHTML=student.name;
newTd1.innerHTML=student.age;
newTd2.innerHTML="语文:"+student.score.chinese+",数学:"+student.score.math+",英语:"+student.score.english;
}
}
};
xmlHttp.open("get","getAjaxInfo?action=JsonArray",true);
xmlHttp.send();
}
</script>
<body>
<div style="text-align: center">
<div>
<input type="button" value="Ajax获取信息" onclick="loadInfo()"/>
&nbsp;&nbsp;姓名:<input type="text" id="name" name="name"/>
&nbsp;&nbsp;年龄:<input type="text" id="age" name="age"/>
</div>
<div style="margin-top: 20px;text-align: center">
<input type="button" value="Ajax获取信息2" onclick="loadInfo2()">
<table id="studentTable" align="center" border="1" cellpadding="0px" style="margin-top: 10px">
<tr>
<th>姓名</th><th>年龄</th><th>得分</th>
</tr>
</table>
</div>
</div>
</body>
</html>

Ajax核心知识(1)的更多相关文章

  1. Ajax核心知识(2)

    对于Ajax核心的东西需要在进行总结提炼一下: xmlHttp对象. 方法:xml.responseText获取后台传递到前台的数据,经常性的使用var object=xml.responseText ...

  2. 对学习Ajax的知识总结

    1.对Ajax的初步认识 1.1. Ajax 是一种网页开发技术,(Asynchronous Javascript + XML)异步 JavaScript 和 XML: 1.2.Ajax 是异步交互, ...

  3. 网络基础知识、ASP.NET 核心知识(1)*

    为什么要写网络? 我原本的计划是这样的,连续两天梳理ASP.NET开发的核心知识.说到这呢,有人问了.“不是说好了做ASP.NET笔记吗?为啥要写网络基础知识?是不是傻?” 原因是这样的.作为网站开发 ...

  4. AJAX重点知识的心得体会

    下面就为大家带来一篇 AJAX重点知识的心得体会.学习还是有点帮助的,给大家做个参考吧. AJAX是什么? 是Asynchronous Javascript And XML的首字母的缩写, 它不是一门 ...

  5. Ajax基础知识 浅析(含php基础语法知识)

    1.php基础语法    后缀名为.php的文件 (1) echo   向页面中输入字符串  <?php    所有php相关代码都要写在<?php ?>这个标签之中 echo &q ...

  6. Ajax基础知识《一》

    对于网站开发人员,一定不会陌生的Ajax技术,本篇就让我们认识一下它,或许在日后的开发过程中我们就可以使用到.Ajax在那方面使用的比较多呢?答案:表单注册,传统的表单注册,有时需要填写大量的信息,当 ...

  7. ASP.NET Ajax核心对象

    本章学习目标 主要掌握AJAX的基本概念和实现机制,学习并创建XMLHttpRequest对象,使用XMLHttpRequestObject对象获取服务器端的数据 主要内容如下,请点击ASP.NET ...

  8. Ajax基础知识(二)

    接上一篇  Ajax基础知识(一) 在上一篇博客里,抛弃了VS中新建aspx页面,拖个button写上C#代码的方式.使用ajax的方式,异步向服务器请求数据.我们让服务器只简单的返回一个" ...

  9. Vuex核心知识(2.0)

    Vuex 是一个专门为 Vue.js 应该程序开发的状态管理模式,它类似于 Redux 应用于 React 项目中,他们都是一种 Flux 架构.相比 Redux,Vuex 更简洁,学习成本更低.希望 ...

随机推荐

  1. Linux 之 2>&1

    我们在Linux下经常会碰到nohup command>/dev/null 2>&1 &这样形式的命令.首先我们把这条命令大概分解下首先就是一个nohup表示当前用户和系统 ...

  2. android v7包的关联

    最近在使用到侧滑栏的时候,使用到了v7包下的actionbar,结果折腾了好久才折腾好,其实很简单的,操作步骤如下: 1. 在eclipse中导入v7包的工程 2. 在自己的工程中打开properti ...

  3. Activity的四种启动模式区别

    (1) standard 模式启动模式,每次激活Activity时都会创建Activity,并放入任务栈中. (2) singleTop 如果在任务的栈顶正好存在该Activity的实例, 就重用该实 ...

  4. 调度工具taskctl跨调度服务依赖实现

    调度工具taskctl虽然支持分布式调度,但是有的时候,不同重要程度的调度服务还是要区分开来,在区分开后,不同调度服务之间怎么实现依赖啦, 其实有很多方式,比如写文件,写数据库之类的,这些都可以根据用 ...

  5. 迅为4412嵌入式安卓开发板兼容3G网络|4G网络

    iTOP-Exynos4412开发板内置有无线 WIFI 模块.Bluetooth.GPS.Camera.3G等模组,陀螺仪等,支持 HDMI1.4(1080P/60Hz)显示,客户可以直接从开发平台 ...

  6. python远程控制电脑

    python拥有大量的第三方库,且语法简单.今天老杨就用python实现远程控制电脑 ​ 所谓,谋定而后动,在实现任何一个需求之前,我们需要先分析,捋清楚一个思路,远程控制电脑,无非就是接收远程的命令 ...

  7. tar (child): lbzip2: Cannot exec: No such file or directory tar (child): Error is not recoverable: exiting now tar: Child returned status 2 tar: Error is not recoverable: exiting now

    tar解压bz2格式 报错 解决方法很简单,只要安装bzip2就行了,yum安装的命令如下: yum -y install bzip2 如果是无法联网,可以去官网下载安装包,进一步安装即可

  8. MFC线程获取主窗口句柄

    CWnd* h_q = AfxGetApp()->GetMainWnd(); //获取主窗口的句柄

  9. WebStorm改变字体大小以及更换背景颜色

    参考文章:https://blog.csdn.net/weixin_42676530/article/details/82961279

  10. javascript脚本的延时加载

    javascript脚本的延时加载 向HTML页面中插入js代码的主要方法是使用<script>标签,在实际的开发中多采用外部文件的方式,主要考虑到外部js代码的可维护性及可缓存性等优点. ...