javascript使用ajax方式

ajax请回和回应实例:

    function showContent(type) {
//create obj
        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("content").innerHTML = xmlhttp.responseText;
            }
        }
//open
        xmlhttp.open("GET", "<?php echo base_url()  ?>Showcontent/sendcontent?type=" + type + "&" + 

Math.random().toString(), true);
//request       
     xmlhttp.send();
    }

function:

1、open(method,url,async):规定请求的类型、URL 以及是否异步处理请求

(1)method:请求的类型;GET 或 POST

(2)url:文件在服务器上的位置

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

2、send(string):将请求发送到服务器

(1)string:仅用于 POST 请求,内容为post的参数,例:xmlhttp.send("ids="+ids+"&id="+id);

3、setRequestHeader(header,value):向请求添加 HTTP 头

(1)header: 规定头的名称

(2)value: 规定头的值

variable:

1、readyState :存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

(1)0: 请求未初始化

(2)1: 服务器连接已建立

(3)2: 请求已接收

(4)3: 请求处理中

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

2、status

(1)200: "OK"

(2)404: 未找到页面

response:

1、onreadystatechange:存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数(需要绑定该回调)

2、response内容:

(1)responseText--获得字符串形式的响应数据

(2)responseXML--获得 XML 形式的响应数据

注意:

1.为防止请求到的数据为缓存数据,在open函数的url上加上的唯一ID(例:http://www.example.com/oa?a=Math.random()

原文地址:https://www.cnblogs.com/yaosj/p/6554753.html