天天看点

原生JS的AJAX请求和jQ的AJAX请求

原生JS的AJAX请求

//第一步,创建XMLHttpRequest对象
var xhr= new XMLHttpRequest();
function CommentAll() {
    //第二步,注册回调函数
    xhr.onreadystatechange =callback1;
    //{
    //    if (xhr.readyState == 4)
    //        if (xhr.status == 200) {
    //            var responseText = xmlHttp.responseText;

    //        }
    //}
    //第三步,配置请求信息,open(),get
    //get请求下参数加在url后,.ashx?methodName = GetAllComment&str1=str1&str2=str2
    xhr.open("post", "/ashx/myzhuye/Detail.ashx?methodName=GetAllComment", true);

    //post请求下需要配置请求头信息
    //xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    //第四步,发送请求,post请求下,要传递的参数放这
    xhr.send("methodName = GetAllComment&str1=str1&str2=str2");//"

}
//第五步,创建回调函数
function callback1() {
    if (xhr.readyState == 4)
        if (xhr.status == 200) {
            //取得返回的数据
            var data = xhr.responseText;
            //json字符串转为json格式
            data = eval(data);
            $.each(data,
                function(i, v) {
                    alert(v);
                });       
        }
}
           
<script>
        function LoadAjax(){
            var date1 = new Date();
            var xmlhttpre;
            if(window.XMLHttpRequest){
                xmlhttpre = new XMLHttpRequest();
            }else{
                xmlhttpre = new ActiveXObject("Microsoft.XMLHTTP")
            }
            xmlhttpre.open("get","http://192.168.137.1:8080/h717/allStk",true)
            // xmlhttpre.open("post", "http://192.168.62.151:8081/login", true)
            // xmlhttpre.setRequestHeader("Content-type","application/x-www-form-urlencoded")
            xmlhttpre.send()
            xmlhttpre.onreadystatechange=function(){
                if(xmlhttpre.readyState==4 && xmlhttpre.status==200){
                    console.log(xmlhttpre)
                    console.log(xmlhttpre.responseText);
                    var result = JSON.parse(xmlhttpre.responseText)
                    console.log(result)
                }
            }
        }
    </script>
    <button onclick="LoadAjax();">点击发送请求</button>
           

jQ的AJAX请求

$(function () {
    //点击按钮 发送ajax请求
    $("#btn").on("click", function () {
        //发送get请求
        $.get("http://127.0.0.1:8080/h717/allStk", function (res) {
            //   console.log(res)  测试请求是否成功
            var jsonObj = eval("(" + res + ")") //把文本转化成对象
            // console.log(jsonObj)  测试数据是否成功转化成数组对象
            if (jsonObj != 'fail') {
                $.each(jsonObj, function (i, v) {
                        console.log(v.stkcode) 拿到所有股票代码
                })
            } else {
                alert("数据接口异常,请检查接口配置")
            }
        })
})
           

部分参考:https://blog.csdn.net/yh12346789/article/details/79271812