我在一个有趣的地方。我对Full-Stack相当陌生,所以我甚至不确定我要做什么是可能的……请耐心听我说。我正在尝试创建一个RSS聚合器,可以通过RSS收集文章的内容,并根据内容过滤它们。无论如何,
我使用ajax调用通过JQuery在一个javascript文件,不附加到任何HTML页面。通过app.js调用
var GetRSS = require('./public/javascripts/GetRSS.js');
在GetRSS文件中:
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('Unable to load feed. Incorrect path or invalid feed.');
},
success: function(xml){ // Save items after successful read. They will eventually go into a database.
values = xml.responseData.feed.entries;
var art = new Article(values);
var pretty = JSON.stringify(values,null,2); // This is for printing purposes (when needed).
console.log("1");
populateArticle(values);
}
但是,当我启动服务器时,它得到以下错误:
$.ajax({
^
ReferenceError: $ is not defined
我尝试包含javascript添加:
var jQuery = require('./jquery.js');
但它没有帮助。为了重复,我现在没有HTML文件,因为它将简单地从DB加载内容,而"GetRSS"文件总是在运行和填充。我在网上看到的所有地方都通过在HTML中使用脚本标签将JQuery与JS文件联系起来。
是否可以利用JQuery库的方式,我正在尝试?如果没有,还有其他选择吗?
jQuery有一个npm
包。您可以使用npm install --save jquery
命令和require
命令在您的Node环境中安装它。
注意,您也可以使用cheerio而不是jQuery来进行DOM操作,并且由于在Node环境中没有XMLHttpRequest
对象,因此您不能发送Ajax请求。对于http请求,您可以使用request
包:
var request = require('request');
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
不能从.js文件运行jquery。你需要创建一个.html页面,并将它和你的GetRSS.js包含在你的文件中进行测试。
的例子:
<html>
<head>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
<script type='text/javascript' src='/public/javascripts/GetRSS.js'></script>
</head>
<body onload="GetRSS()">
</body>
</html>
修改GetRSS.js:
function GetRSS() {
alert('GOT THE EXTERNAL RSS!');
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('Unable to load feed. Incorrect path or invalid feed.');
},
success: function(xml){ // Save items after successful read. They will eventually go into a database.
values = xml.responseData.feed.entries;
var art = new Article(values);
var pretty = JSON.stringify(values,null,2); // This is for printing purposes (when needed).
console.log("1");
alert('FOUND ENTRY!');
populateArticle(values);
}
});
}
你应该能够运行你的代码没有问题。