標籤:api ajax
寫介面的話,無非就為了讓移動端,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