ajax(一)

本文介绍了Ajax技术的基本概念,包括异步的JavaScript和XML如何用于创建快速动态网页,详细讲解了XMLHttpRequest对象的创建、使用方法及请求类型(GET与POST),并展示了如何处理服务器响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、ajax简介

 异步的javascript和xml

创建快速动态网页的技术

通过在后台与服务器进行少量的数据交换,不用重新加载整个页面,只需要对网页某部分进行刷新

二、XMLHttpRequest

1、是ajax的基础

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

3、

①创建XMLHttpRequest对象

 

var xmlhttp;

if(window.XMLHttpRequest){//如果支持XMLHttpRequest对象,则创建一个XMLHttpRequest对象

    xmlhttp= new XMLHttpRequest();

}else{

   xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");//否则创建ActiveX对象

}

②用于和服务器交换数据(所以就有请求和响应)

open(method,url,async)

     method:规定请求类型

     url:文件在服务器上的类型

     async:同步(false)还是异步(true)

PS:

点击按钮执行HTTP请求然后跳转下一页:
同步:发送http请求→获取返回结果→分析结果→跳转下一页
异步:发送http请求→跳转下一页(不需要等待请求结果,对结果的处理在另一个线程中)

(一般大部分都是异步请求)

send(string):将请求发送到服务器   string:仅用于 POST 请求

A。get请求

<!--StartFragment -->
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","/ajax/demo_get2.asp?fname=Bill&lname=Gates",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</body>
</html>

B。post请求

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","/ajax/demo_post2.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据<button>
<div id="myDiv"></div>

</body>
<xml>

三、响应

responseXML 获得 XML 形式的响应数据。

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

四、

属性:status:200--ok;404--未找到页面

           readystate:0--请求未初始化

                             1--服务连接已建立

                             2--请求已接收

                             3--请求处理中

                             4--请求已完成且响应已就绪

方法:onreadystatechange()--每当readystate属性改变时都会调用这个函数

         

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值