在codeigniter采用JQuery的$.ajax方法调取api数据
本帖最后由 lanwailan 于 2016-1-16 10:01 编辑首先在api_model.php 中写入调取api接口数据的文件<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Api_model extends CI_Model{
public function find_num($num){
$ch = curl_init();
$url = 'http://apis.baidu.com/apistore/mobilenumber/mobilenumber?phone='.$num;//这里用的是百度免费的api
$header = array(
'apikey: *************', ); // 添加apikey到header
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); // 添加apikey到header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 执行HTTP请求
curl_setopt($ch , CURLOPT_URL , $url);
$res = curl_exec($ch);
$data=json_decode($res,TRUE);
return $data;
}}
在controller中写入如下代码: public function api(){
$segments=$this->uri->uri_to_assoc(); //默认是3
$this->load->model('api_model','api');
$data['find_num']=$this->api->find_num($segments['number']);
if($data['find_num']['errNum'] ==0){
echo '该手机号码来自:'.$data['find_num']['retData']['city'].'<br />';
echo '运营商为:'.$data['find_num']['retData']['supplier'];
}else{
echo '错误:'.$data['find_num']['retMsg'];
};
}
在view视图中: <label>输入手机号码:</label>
<input type="text" id="number"><p id="txtHint"></p>
<button class="btn btn-default" id="button">查询手机归属地</button>
在javascript中写入: <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var number=$("#number").val();
var oajax= $.ajax({
type:'GET',
url:'<?php echo site_url('home/api/number')?>'+'/'+number,//不知为何只采用<?php echo site_url('home/api/')?>,然后添加data行,controller无法接收到number的数据
dataType:'text',//
success:function(data){
alert('查找成功!');
$('#txtHint').html(data);
return true;
},
error:function(){
alert('failed');
return false;
}
});
});
});
</script>
这样写完的话,相比上篇文章代码更加简洁点,另外将api写入了model函数,与CI较为不错的结合在一起.
原文地址:http://lanwailan.com/index.php/home/article/15
飘过~~~~~~~~~~~~~~~~~~~~~
页:
[1]