js动态调用方法的函数:
// 添加指定位置的js(url eg. js/my.js) function addScript(url) { var script = document.createElement(‘script‘); script.setAttribute(‘type‘, ‘text/javascript‘); script.setAttribute(‘src‘, url); document.getElementsByTagName(‘head‘)[0].appendChild(script); } // 调用指定名称的方法,有一个入参 function call(funcName, par) { var target = funcName + "(‘" + par + "‘)"; var res = eval(‘(‘ + target + ‘)‘); // 如果返回值是json对象,必须按照此格式,多加一层括号,因为json外部是{}包住,会被js误认为是执行脚本 return res; } $(function(){ $("#btnTest").click(function () { var res = call(‘fun1‘, ‘myApp‘); if (res == null) { alert("获取数据异常"); return; } if (res.code == "200") { if (!res.content) { alert("无信息"); return; } alert(res.content); } else alert(res.message); }); });
如,类似有如下my.js:
function fun1(appName) { var url = "http://127.0.0.1:12345/api/version?app=" + appName+ ""; //jQuery.support.cors = true; var obj = { code: "300", message: "", content: "" }; $.ajax({ url: url, timeout: 2000, type: "get", dataType: "json", async: false, success: function (data) { obj.code = data.Code; obj.message = data.Message; obj.content = data.Content; }, error: function (e, d) { console.log(e); obj.code = "500"; obj.message = e.statusText; obj.content = ""; } }); return obj; }