ajax配合json拿取Java或者PHP接口数据

以下仅为本人学习使用

主要是

AJAX-XHR(创建对象)

AJAX-XHR(请求)

AJAX-XHR(响应)

AJAX-XHR(readyState)

1.创建对象

为了兼容ie5和ie6:

var xmlhttp;

if(window.XMLHttpRequest){

     xmlhttp = new XMLHttpRequest()

}else{

     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

}

2.请求

使用XMLHttpRequest 对象的 open() 和 send() 方法

使用get时

xmlhttp.open("GET","URL?fname=Henry&lname=Ford",true);

xmlhttp.send();

使用post时,需要使用 setRequestHeader() 来添加 HTTP 头,然后在 send() 方法中规定希望发送的数据

xmlhttp.open("POST","URL",true);

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

xmlhttp.send("fname=Henry&lname=Ford");

3.响应

获得来自服务器的响应,就需要使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性

responseText属性返回字符串形式的响应

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,就使用 responseXML 属性

xmlDoc=xmlhttp.responseXML;

 txt="";

x=xmlDoc.getElementsByTagName("ARTIST");

for (i=0;i<x.length;i++)

{txt=txt + x[i].childNodes[0].nodeValue + "<br>";}

document.getElementById("myDiv").innerHTML=txt;

4.readyState

readyState 属性存有 XMLHttpRequest 的状态信息

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

XMLHttpRequest 对象的三个重要的属性

当 readyState 等于 4 且状态为 200 时,表示响应已就绪

xmlhttp.onreadystatechange=function()

{

    if (xmlhttp.readyState==4 && xmlhttp.status==200)

    {

        document.getElementById("test").innerHTML=xmlhttp.responseText;

    }

}

json字符串,JSON 比 XML 更小、更快,更易解析,我们可以使用:

JSON.parse() 方法将json字符串数据转换为 JavaScript 对象

JSON.stringify() 方法将 JavaScript 对象转换为json字符串字符串

一下是一个完整的get请求示例

        var xmlhttp;
        if(window.XMLHttpRequest){
            xmlhttp = new XMLHttpRequest();
        }else{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
        }
        xmlhttp.open("GET","http://127.0.0.1/Reception/interface/getdata.php")
        xmlhttp.send();
        xmlhttp.onreadystatechange=function(){
            if(xmlhttp.readyState == 4 &&xmlhttp.status ==200){
                //将json字符串转化为JavaScript对象
                var data = JSON.parse(xmlhttp.responseText).data;
                console.log(data);
                console.log(data.length);
            }
        }

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值