js ajax请求

Ajax API

var reqUrl = "http://192.168.31.162:8081/obtain/onlineState?name=aa01&password=010203";
var postUrl = "http://192.168.31.162:8081/update/remoteClientInfo";
/**
 * 页面
 *    http://192.168.31.162:8081/http/ajax/Aj01-HttpRequest.html
 * ajax get 请求
 *  http://www.w3school.com.cn/ajax/ajax_xmlhttprequest_send.asp
 */
function testAjaxGet() {
    debugger;
    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.open("GET", reqUrl, true);
//        xmlhttp.open("GET", reqUrl, false);
    xmlhttp.send();
//        console.log(xmlhttp.responseText);
    xmlhttp.onreadystatechange = function () {  // 异步方法回调
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            console.log(xmlhttp.responseText);
        }
    }
}
/**
 * Ref:
 *
 */
function testAjaxPost() {
    debugger;
    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.open("POST", postUrl, true);
//        xmlhttp.open("POST", postUrl, false);
    xmlhttp.setRequestHeader("Content-type","application/json");
    var jsonObj = {
        name:"AAA"
    };
    xmlhttp.send(JSON.stringify(jsonObj));
//        console.log(xmlhttp.responseText);
    xmlhttp.onreadystatechange = function () {  // 异步方法回调
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            console.log(xmlhttp.responseText);
        }
    }
}

允许跨域的几种方案

/**
 * 跨域问题解决方案:
 *  P1.使用websocket代理请求;
 *  P2.设置服务器允许跨域请求;
 *      http://www.jb51.net/article/109725.htm
 *      http://blog.csdn.net/flower46273736/article/details/62889077
 *      http://www.jb51.net/article/95268.htm
 *  P3.JSONP方式;--验证未通过
 *      http://blog.csdn.net/joyhen/article/details/21631833
 *  P4.服务器代理连接;
 *
 */
httpReq.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:63342");    // 指定支持域名
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

 

参考:

     AJAX - 向服务器发送请求 w3c

posted @ 2017-10-09 22:37  zhen-Android  阅读(277)  评论(0编辑  收藏  举报