加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:09:50 所属栏目:百科 来源:网络整理
导读:写接口的话,无非就为了让移动端,WEB端,或者是PC Client调用。 我们写个返回JSON格式的接口,功能是关于四则运算。 ?php header('Content-type:application/json'); $operator = $_GET['operator']; $first = $_GET['first']; $second = $_GET['second'];

写接口的话,无非就为了让移动端,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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读