js使用XMLHttpRequest实现跨域请求 POST请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery.js"></script>
</head>
<body>
<button οnclick="xmlhttp()">xmlhttp</button>
</body>


<script>
    function getHttpObj() {
        var httpobj = null;
        try {
            httpobj = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                httpobj = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e1) {
                httpobj = new XMLHttpRequest();
            }
        }
        return httpobj;
    }

    function xmlhttp() {
//        var xhr = new XMLHttpRequest();
        var xhr = getHttpObj();
        xhr.open("post", "http://www.abcd.com/*****", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");//缺少这句,后台无法获取参数
        xhr.onreadystatechange = function() {
            console.log(xhr.responseText);
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText);
            }
        };
        var content = "appid=11111&sign=222222222";
        xhr.send(content);
    }

</script>

</html>

使用js编写跨域http的post请求

注意,服务器端须设置设置response'Access-Control-Allow-Origin',

有些朋友可能会用ajax的jsonp方法,但是jsonp只能提供get请求,对于限制post请求的接口则无法适用。

关于jsonp的实现原理,参照http://www.jb51.net/article/75669.htm

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值