写接口的话,无非就为了让移动端,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>
原文地址:http://blog.csdn.net/xeay123/article/details/42269591