当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js回调函数在项目中的运用

js回调函数在项目中的运用

2017年12月21日  | 移动技术网IT编程  | 我要评论

js回调函数在项目中的运用,js回调函数用处非常多,现在我就简单的介绍点基础的。
代码:

var senderId = $.cookie("senderId");
var secToken = $.cookie("secToken");
var userName = $.cookie("userName");
var urlPath = "../../develop/";

var popu;
var popu2;
var seme = [];



//写一个绑定课程的方法

var  registerCourse = {


     getCurrentSemester:function(jsondata){
        var  action = "Lab_getCurrentSemester";

        return  ajaxdata(action,jsondata);

     },

     getCourse:function(jsondata){
        var action = "Lab_getLabCourseList";

        return ajaxdata(action,jsondata);   

     }

 }


function ajaxdata(action,jsondata){


    var returnvalue ;
    var callback = function(func,msg){

        return func(msg);
    }
    var func = function(msg){

        console.log("回调函数执行了");
        console.log(msg);


        returnvalue = msg;

        console.log(returnvalue);
        //获取学期的判断
        if(msg.localSemester !=null){

            returnvalue = msg.localSemester;
        }
        //课程的数据
        if(msg.localCourselist !=null){

            returnvalue = msg.localCourselist;
        }


        return returnvalue;
    }





    $.ajax({
        async:false,
        dataType:"json",
        type:"post",
        url:urlPath+action,
        data:jsondata,
        success:function(msg){

            console.log(msg);

            console.log("success");

            console.log(func+msg.localSemester)

            callback(func,msg);
        },
        error:function(){

            alert("请求失败");
        }

    })


    console.log(returnvalue);
    return returnvalue;
}



//alert(registerCourse.getCurrentSemester(jsondata));



$(function() { 
    //注册课程的操作

    $("#registercourse").click(function(){

        $(".xiaochu").remove();
        var year = $("#year").val();
        var semester = $("#semester").val();

        console.log(year+semester);
        //changesemester(semester);


        $("#yearin").val(year);

        console.log(changesemester(semester));

        $("#semesterin").val(changesemester(semester));

        var jsondata ={
                senderId:senderId,  
                secToken:secToken,
                semester:semester,
                year:year,
        }
        var semester =  registerCourse.getCurrentSemester(jsondata);


        var course =  registerCourse.getCourse(jsondata);


        console.log("获取结果");
        console.log(semester);

        console.log(course);


            $.each(course ,function(index,row){

                console.log(row);
                if(row.localName != null){
                    $("#coursecodein").append("
"+row.localName+""); } }) $("#mymodal").modal("toggle"); }); )}

我们在webservice的项目或者其他项目中经常出现这样的操作,ajax请求数据,服务器的得到相应给数据,处理数据,页面上的action调用数据,这段代码的思想就是封装一个函数类,action时候调用类,给变量调用类的方法,将共有的部分封装ajaxdata函数里面回调函数获取ajaxsuccess的数据,并处理。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网