微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax连接后端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>ajax</title>
    <script>
        window.onload = function () {
            var
                oSend = document.getElementById('send');
            oSend.onclick = function () {
                var xmlHttp = null;
                if(window.ActiveXObject){
                    xmlHttp = new window.ActiveXObject('Microsoft.XMLHTTP');
                } else {
                    xmlHttp = new XMLHttpRequest();
                }

                /*GET方法
                // 指定请求方式
                 xmlHttp.open('GET','http://localhost/ajax/ajax.PHP?username=jimmy&age=28',true);
                //发送请求
                xmlHttp.send();*/

                //POST方法
                xmlHttp.open('POST','http://localhost/ajax/ajax.PHP',true);
                xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
                //发送请求
                xmlHttp.send('username=jiming&age=28');

                //等待接收结果
                xmlHttp.onreadystatechange = function(){
                    if(xmlHttp.readyState == 4){
                        if(xmlHttp.status === 200) {
                            // console.log(xmlHttp.responseText);
                            // console.log(xmlHttp.statusText);
                            /* aCity = xmlHttp.responseXML.getElementsByTagName()
                            console.log(xmlHttp.responseXML);//返回xml对象*/

                        }
                    }
                }
            }
        }
    </script>
</head>
<body>
<button id="send">发送</button>
</body>
</html>

后端PHP代码

<?PHP
	header("Access-Control-Allow-Origin:*");
	//$username = $_GET['username'];
	//$age = $_GET['age'];
	$username = $_POST['username'];
	$age = $_POST['age'];
	echo '我叫'.$username.'今年:'.$age;
?>

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐