<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS</title> <style> #box{ width:600px; height:200px; padding:20px; border:1px solid #999; } </style> </head> <body> <h1>ajax get方式传递参数</h1> <hr> Number1: <input type="text" id="num1"><br> Number2: <input type="text" id="num2"><br> <button onclick="loadHtml()">加载</button> <div id="box"></div> <script> function loadHtml(){ //获取表单中的数据 var num1 = document.getElementById('num1').value; var num2 = document.getElementById('num2').value; //实例化 XMLHttpRequest对象 if(window.XMLHttpRequest){ //非IE var xhr = new XMLHttpRequest(); }else{ var xhr = new ActiveXobject('Microsoft.XMLHTTP'); } //给xhr 绑定事件 检测请求的过程 xhr.onreadystatechange = function(){ console.log(xhr.readyState); //如果成功接收到响应 if(xhr.status == 200 && xhr.readyState == 4){ document.getElementById('box').innerHTML = xhr.responseText; } } //进行请求的初始化 xhr.open('get', 'js.php?n1='+num1+'&n2='+num2, true); //正式发送请求 xhr.send(); } </script> </body> </html>
<?php echo $_GET['n1'] + $_GET['n2']; ?>