AJAX基础总结(参考w3school)

1.创建XMLHttpRequest对象
var williaml;
if(window.XMLHttpRequest)
{
    //for IE7,Firefox,Chrome,Opera,Safari
    william=new XMLHttpRequest();
}
else
{
    //for IE6,IE5
    william=new ActiveXObject("Microsoft.XMLHTTP");
}
    



2.如果要把请求发送到服务器,使用XMLHttpRequest的open()和send()方法

GET

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
    var william;
    if(window.XMLHttpRequest)
    {
        william=new XMLHttpRequest();
    }
    else
    {
        william=new ActiveXObject("Microsoft.XMLHTTP");
    }
    william.onreadystatechange=function()
    {
        if(william.readyState==4&&william.status==200)
        {
            document.getElementById("my").innerHTML=william.responseText;
        }
    }
    william.open("GET","/ajax/demo.asp?name=bill&age=56",true);
    william.send();
}
</script>
</head>
<body>

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

</body>
</html>



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" οnclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
 
</body>
</html>

在与后台交互的时候,通常是这样子写:(找了个例子)

$.ajax({
            type : "POST",                         //请求方法
            contentType : "application/json",     //发送到服务器的数据的编码类型
            dataType : "json",                   //预期返回类型
            url : "searchController.do?getValidateCode&phoneCode="+$("#accountPhone").val(),// 当前页地址。发送请求的地址
            success : function(data) {          //请求成功后的回调函数     
                if(!data.success){
                    alert(data.obj);
                }
            },
            error : function() {               //请求失败时调用此函数
                alert("抱歉,暂时无法为您提供这项服务。");
            }
        });


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值