js实验-AJAX入门

版权声明:本文为博主原创,转载请注明出处 https://blog.csdn.net/fireflylane/article/details/84504349

 

用AJAX实现如下功能,点击后返回算数表达式的值

 

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <p>我们使用AJAX方式来计算1和2的和</p>
    <button onclick="cal()">计算</button>
    <p id="sum"></p>
    <script src="./ajax.js"></script>
</body>
</html>
//JavaScript
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
    if((xhr.readyState==4)&&(xhr.status==200)){
        document.getElementById("sum").innerHTML=xhr.responseText;
    }
}

function cal()
{
    xhr.open("GET","http://127.0.0.1:50000/ajax.php?a=1&b=2",true);
    xhr.send();
}
//php
<?php
    header("Access-Control-Allow-Origin:*"); //解决chrome浏览器产生的问题
    $sum = $_GET['a'] + $_GET['b'];
    echo "结果是:",$sum;
?>

猜你喜欢

转载自blog.csdn.net/fireflylane/article/details/84504349
今日推荐