赞
踩
今天扣出一段js想用execjs执行,报错$未定义,也就是说execjs不能执行jquery,决定试试用nodejs来执行。
execjs._exceptions.ProgramError: ReferenceError: $ is not defined
1、安装jsdom
cnpm i jsdom -g
2、安装 jquery
cnpm i jquery -g
3、查询全局引用路径,方便execjs调用
cnpm root -g
返回我的安装路径:D:\Program Files\nodejs\node_modules
如果使用npm,则
npm root -g
返回我的安装路径:C:\Users\Administrator\AppData\Roaming\npm\node_modules
jQueryDomstr = ''' var jsdom = require('jsdom'); const { JSDOM } = jsdom; const { window } = new JSDOM(); const { document } = (new JSDOM('')).window; global.document = document; var $ = jQuery = require('jquery')(window); ''' jsstr = ''' commitAnswerToBackStage = function(k, a, g, d, f, i, c,sk,cookie) { $.ajax({ type: "post", url: "http://www.example.com/ess/service/myexam/myExamAo!doCommitExam.do", async: false, data: { myExamAnswer: k.toString(), userAccount: a, domainCode: g, examId: d, paperId: f, series: i, sid: c, secretKey: sk, }, beforeSend:function(request){ request.setRequestHeader("Cookie",cookie); }, headers:{ 'Connection': "Keep-Alive", 'Content-Type': "application/x-www-form-urlencoded;charset=UTF-8", 'Accept': "application/json, text/javascript, */*; q=0.01", 'X-Requested-With':"XMLHttpRequest", 'Referer':"http://www.example.com/bps/index.html", 'User-Agent':"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36", 'Cookie':cookie, }, dataType: "json", success: function(n) { console.log(n) }, error: function() { console.log("error") } }); } ''' rid = self.session.cookies['rid'] print(rid) cookie = 'fxInd=I; fxCode=Aundefined; rid=' + str(rid) jsrt = jQueryDomstr+jsstr compile_js = execjs.compile(jsrt,cwd=r'C:\Users\Administrator\AppData\Roaming\npm\node_modules') # 这里是上一步查询出来jquery安装路径 result = compile_js.call("commitAnswerToBackStage", str(h), int(userAccount), int(domainCode), int(examId), int(paperId),int(series),str(ssid),str(secretKey),cookie) return result
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。