动态引进js文件

在项目中遇到一个这样的问题。即:进行登录以后才引进并执行一个外部的js文件。代码如下:

//动态引进js,登录成功后引入holdSession.js
  function loadScript(url, callback) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    if(typeof(callback) != "undefined") {
      if(script.readyState) {
        script.onreadystatechange = function() {
          if(script.readyState == "loaded" || script.readyState == "complete") {
            script.onreadystatechange = null;
            callback();
          }
        };
      } else {
        script.onload = function() {
          callback();
        };
      }
    };
    script.src = url;
    document.body.appendChild(script);
  }

 

//点击登陆
function fun_login(_type) {
  //检查录入项目:
  var err = checkLogin();
  if(err) {
    alert(err);
    return;
  }
  var formData = {
    "loginType": _type,
    "loginName": $(".login-right input[name='loginname']").val(),
    "password": $(".login-right input[name='password']").val()
  };
  $.ajax({
    type: 'post',
    url: "/dp/spirit/login",
    data: formData,
    dataType: 'json',
    success: function(data) {
      if(data.returnCode == "00") {
        isLogin = "1";
        var memberObjStr = JSON.stringify(data.memberInfo);
        sessionStorage.setItem("cgpt_memberInfo", memberObjStr);
        sessionStorage.setItem("cgpt_pwd", $(".login-right input[name='password']").val());
        $("#signBox").html("");
        $("#signModal").modal("hide");
        fillMemberMes(memberObjStr);
        loadScript("/dp/cgpt/js/holdSession.js", function() {
          //加载,并执行回调函数
        });
      } else {
        alert("登录失败:" + data.messageInfo);
      }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { //失败回调函数
      var m = "系统错误:\nstatu=" + XMLHttpRequest.status + "\nreadyState=" + XMLHttpRequest.readyState + "\ntext=" + textStatus + "\nerrThrown=" + errorThrown;
      alert(m);
    }
  });

 

posted @ 2018-05-03 15:33  TigerZhang  阅读(418)  评论(0编辑  收藏  举报