Ajax实例一:利用服务器计算

Ajax实例一:利用服务器计算

HTML代码

//输入两个数
<input id="number1" type="number">
<input id="number2" type="number">

//查询按钮
<button onclick="askServer()">Ask the Server</button>


//返回结果显示区
<p id="result"></p>

JavaScript代码

//创建一个XMLHttpRequest对象实例
var req = new XMLHttpRequest();

function askServer() {
  //获取两个值
  var number1 = document.getElementById("number1").value;
  var number2 = document.getElementById("number2").value;

  //构建查询字符串
  var dataToSend = "?number1=" + number1 + "&number2=" + number2;
  
  //发送请求
  req.open("GET", "WebCalculator.php" + dataToSend, true);
  
  //监控程序等待远程主机做出回应
  req.onreadystatechange = handleServerResponse;
  
  req.send();
  
  document.getElementById("result").innerHTML = "The request has been sent.";
}


function handleServerResponse() {
  if ((req.readyState == 4) && (req.status == 200))//数据已经接收完毕且正常
 {
    var result = req.responseText;//把响应文本赋值给result
    
    document.getElementById("result").innerHTML = "The answer is: " + result;
  }
}

服务器端代码:WebCalculator.php


<?php
       $num1 = $_GET['number1'];
       $num2 = $_GET['number2'];
echo ($num1 + $num2); 
?>
posted @ 2017-01-22 06:34  叶子陪你玩  阅读(239)  评论(0编辑  收藏  举报