1. 申请第三方接口
我这里使用了第三方数据商“聚合数据”的接口(https://www.juhe.cn),然后申请它的手机号码归属地接口,如下图所示(在“数据中心”->“我的接口”处)得到key
2. 前端样式和JS校验
写一个简单的前端样式
前端的JS校验代码如下:
$(document).ready(function(){
$('#subPhone').click(function(){
var phone = $('#phoneText').val();
IMOOC.GLOBAL.ajax('api.php', 'post', {phone: phone}, 'json', IMOOC.APPS.QUERYPHONE.dataCallback);
});
});
var IMOOC = IMOOC || {};
IMOOC.GLOBAL = {};
IMOOC.APPS = {};
IMOOC.APPS.QUERYPHONE = {};
IMOOC.APPS.QUERYPHONE.showInfo = function(){
$('#phoneInfo').show();
};
IMOOC.APPS.QUERYPHONE.hideInfo = function(){
$('#phoneInfo').hide();
};
IMOOC.APPS.QUERYPHONE.dataCallback = function(data) {
if (data.code == 200) {
IMOOC.APPS.QUERYPHONE.showInfo();
$('#phoneNumber').text(data.phone);
$('#phoneProvince').text(data.provincecity);
$('#phoneCatName').text(data.phoneCatName);
$('#phoneMsg').text(data.msg);
} else {
IMOOC.APPS.QUERYPHONE.hideInfo();
alert(data.msg);
}
};
IMOOC.GLOBAL.ajax = function(url, method, params, dataType, callback){
$.ajax({
url: url,
type: method,
data: params,
dataType: dataType,
success: callback,
error:function(){
alert('请求异常');
}
});
};
3. 后台逻辑处理和API接口
1)API接口
2)号码校验
3)整体代码
header('content-type:text/html;charset=utf8');
$apiurl='http://apis.juhe.cn/mobile/get';
$params=$_POST;
$phone=isset($_POST['phone'])?$_POST['phone']:'';
//验证号码
$ret=false;
if($phone){
if(preg_match('/^1[34578]{1}\d{9}/',$phone)){
$ret=true;
if($ret){
$params = array(
'key' => 'f4dc095bbe9d801cf1b8e8e71c9e422b',
//您申请的手机号码归属地查询接口的appkey
'phone' => $phone
//要查询的手机号码
);
$paramsString = http_build_query($params);
$content = @file_get_contents($apiurl.'?'.$paramsString);
$result = json_decode($content,true);
if($result['error_code'] == '0'){
$data=$result['result'];
//电话
$data['phone']=$phone;
//省份+城市名
$data['provincecity']=$data['province'].$data['city'];
//运营商
$data['phoneCatName']=$data['company'];
//其他
$data['msg']='由聚合数据第三方提供数据';
//删除不必要的数据,减少数据传输
unset($data['company']);
unset($data['zip']);
unset($data['card']);
unset($data['province']);
unset($data['areacode']);
unset($data['city']);
$data['code']=200;
}
}else{
$data['msg']='出现未知错误';
$data['code']=400;
}
}else{
$data['msg']='电话号码格式不正确';
$data['code']=400;
}
}else{
$data['msg']='未输入电话号码';
$data['code']=400;
}
echo json_encode($data);
4. 实战演示