繁体   English   中英

从JavaScript加载外部JavaScript库/脚本

[英]Load external JavaScript libraries/scripts from JavaScript

我正在尝试使用JavaScript / Node.js构建控制台应用程序,以下script.js抛出ReferenceError: $ is not defined编译时ReferenceError: $ is not defined

//user input from command line
var readline = require('readline');

var rl = readline.createInterface({
 input: process.stdin,
 output: process.stdout
});

rl.question("Would you like to see which Car Types are available? Please type yes/no ", function(answer) {
// if yes, print search results to console in descending price order 
if (answer === 'yes'){

var results= "";
$.getJSON("https://techtest.rideways.com/dave/?pickup=3.410632,-2.157533&dropoff=3.410632,-2.157533", function(data){
results = JSON.parse(data);
}); 

console.log("The following Car Types are available:", results.options['car_type'], " - ", results.options['price']);
}else{
console.log("No worries, have a nice day!");
}
rl.close();
});

如这篇文章所示; ReferenceError:未定义$,我希望它是因为缺少JS库。

有没有一种方法可以在我的script.js中调用JS库而无需创建单独的HTML文件? 由于我没有构建前端Web应用程序,因此看不到创建HTML文件的意义吗?

在Node.js代码中,通常不需要使用jQuery,但如果愿意,可以将其作为npm模块使用。 您将安装它( npm install jquery ),然后像在代码中require d readline一样require它。 此答案中的完整细节(由于jQuery需要DOM环境)。

但是 ,这里不需要jQuery。 请使用http.requesthttps.request或类似名称。 我怀疑$.getJSON甚至可以在Node.js中工作。

$看起来像是来自某些jQuery代码的复制/粘贴。 代替jQuery,axios将在Node和浏览器中完成工作。 axios是一个带有axios的http请求库。 首先,将软件包添加到项目中: $ npm i -s axios

获取请求示例:( 在repl.it上运行

const axios = require('axios');

main();

function main() {
  return exampleRequest().then(renderResponseData)
}

function exampleRequest() {
  const url = 'https://techtest.rideways.com/dave/?pickup=3.410632,-2.157533&dropoff=3.410632,-2.157533';

  return axios.get(url)
}

function renderResponseData(response) {
  console.log(response.data)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM