无脑简单有暴力的AJAX。get访问API

写接口的话,无非就为了让移动端,WEB端,或者是PC Client调用。

我们写个返回JSON格式的接口,功能是关于四则运算。

<?php
header(‘Content-type:application/json‘);
$operator = $_GET[‘operator‘];
$first    = $_GET[‘first‘];
$second   = $_GET[‘second‘];  
if($operator == ‘jia‘){  //加法
$result =$first+$second;
}
else if($operator == ‘jian‘){ //减法
$result = $first-$second;
}
else if($operator == ‘cheng‘){ //乘法
$result = $first*$second;
}
else{ //除法
$result = $first/$second;
}
$result = array(‘res‘=>$result,‘status‘=>1);
echo json_encode($result);//返回JSON数据格式 
?>




<!DOCTYPE html>
<meta charset=‘utf-8‘>
<script></script>
<center>
<input type=‘text‘ name=‘first‘ id=‘first‘>
<input type=‘text‘ name=‘second‘ id=‘second‘>
<hr>
<button value=‘jia‘ >加法</button>
<div id=‘jia‘></div>
<hr>
<button value=‘jian‘ >减法</button>
<div id=‘jian‘></div>
<hr>
<button value=‘cheng‘ >乘法</button>
<div id=‘cheng‘></div>
<hr>
<button value=‘chu‘ >除法</button>
<div id=‘chu‘></div>
</center>
<script src=‘jquery.js‘></script>
<script>
$(function(){
$(‘button‘).click(function(){
var first    = $(‘#first‘).val();
var second   = $(‘#second‘).val();
var operator = $(this).val();
var area     = operator;
var query = ‘http://localhost/api.php/?‘+‘first=‘+first+‘&second=‘+second+‘&operator=‘+operator; 
$.get(query,‘‘,function(data,st){ //$.get(我们要输入的URLget串,参数留空,callback)
$(‘#‘+area).text(data.res);         //按了哪个运算的按钮,就要在该区域赋值
});
});
});
</script>

无脑简单有暴力的AJAX。get访问API

上一篇:在Windows cmd中计算行数


下一篇:WPF快速入门系列(9)——WPF任务管理工具实现