angular1的service.js中,可以全局注入使用,别的框架是一样的。初始化 调用。
visaForm.factory('necaptchafn',['LanguageTranslate','$http','$rootScope','projectUrl',function(LanguageTranslate,$http,$rootScope,projectUrl){
return {
embedcaptcha:function(captchaObj){//插入式的
var defineobj = {
captchaId: '9c5b8b9efd934c54aa0bbb3e710ef888',
element: '#captchacontainer',
mode: 'embed',
width: '350',
lang: LanguageTranslate.languageCatche($rootScope.language),
url:projectUrl.url + "captcha/api/v1/verifyCaptcha",
successjudgement:true,
ifneeddestroy:false,
ifneedrefresh:false,
successarg:'',
successcb:function(){console.log('success')},
failcb:function(){console.log('fail')},
elsefn:null
};
var captchaIns;
var ccaptcha = null;
var targetobj = Object.assign(defineobj,captchaObj)
initNECaptcha({
captchaId: targetobj.captchaId,
element: targetobj.element,
mode: targetobj.mode,
width: targetobj.width,
lang: targetobj.lang,
onReady: function (instance) {
captchaIns = instance
// 验证码一切准备就绪,此时可正常使用验证码的相关功能
},
onVerify: function (err, data) {
ccaptcha = data;
/**
* 第一个参数是err(Error的实例),验证失败才有err对象
* 第二个参数是data对象,验证成功后的相关信息,data数据结构为key-value,如下:
* {
* validate: 'xxxxx' // 二次验证信息
* }
**/
if (err) return // 当验证失败时,内部会自动refresh方法,无需手动再调用一次
// 点击登录按钮后可调用服务端接口,以下为伪代码,仅作示例用
if(ccaptcha !== null){
if(targetobj.successjudgement){
$http.post(
targetobj.url,
{captchaId: targetobj.captchaId, validate:ccaptcha}
)
.success(function () {
if(targetobj.successarg){targetobj.successcb(targetobj.successarg)
}else{
targetobj.successcb()
}
if(targetobj.ifneeddestroy){
captchaIns.destroy();
}
})
}else{
targetobj.failcb();
if(targetobj.ifneedrefresh) captchaIns.refresh();
}
}
else {
if(elsefn)elsefn();
}
}
});
},
appendcaptcha:function(captchaObj){//弹出式,插入到html,这样黑色的遮罩层就是整体的。。
var captchaIns;
var ccaptcha = null;
var defineobj = {
captchaId: '9c5b8b9efd934c54aa0bbb3e710ef888',
element: '#captchacontainer',
mode: 'popup',
width: '350',
target2insert:'HTML',
successjudgement:true,
lang: LanguageTranslate.languageCatche($rootScope.language),
successcb:function(){console.log('success')},
failcb:function(){console.log('fail')},
};
var targetobj = Object.assign(defineobj,captchaObj)
initNECaptcha({
captchaId: targetobj.captchaId,
element: targetobj.element,
mode: targetobj.mode,
width: targetobj. width,
appendTo: targetobj.target2insert,
lang: targetobj.lang,
onVerify:function(err, data){
ccaptxt = data;
if (err) return // 当验证失败时,内部会自动refresh方法,无需手动再调用一次
// 点击登录按钮后可调用服务端接口,以下为伪代码,仅作示例用
if($scope.ccaptxt !== null){
if(targetobj.successjudgement){
$http.post(
projectUrl.url + "captcha/api/v1/verifyCaptcha",
{captchaId: targetobj.captchaId, validate:ccaptxt}
)
.success(function () { targetobj.successcb()})
}
}
else {
targetobj.failcb()
}
},
},
function onload (instance) {
// 初始化成功
captchaIns = instance;
captchaIns.popUp();
},
function onerror (err) {
// 验证码初始化失败处理逻辑,例如:提示用户点击按钮重新初始化
})
}
}
}]);