这是我将请求消息发送到服务器并取回响应并打印出来的小代码片段。这是一个 chrome 插件,但问题是如果在浏览器上发生任何 onClick 操作,那么它将获取 url 并必须发送到另一个 JavaScript 文件,然后这个 JavaScript 文件负责将 url 发送到 node.js 服务器
url.js(在点击时获取 url)文件是:
$(document).click(function (e) {
if ($(e.target).closest('a').length) {
// I want this url variable to be transferred from here to the below
// JavaScript file
var url = $(e.target).closest('a').attr('href');
} else {
alert('You did not click a link');
}
});
另一个接受参数的 javascript 文件是:
window.WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://localhost:1337');
connection.onopen = function () {
connection.send(url);
connection.send("http://static.adzerk.net/Advertisers/bd294ce7ff4c43b6aad4aa4169fb819b.jpg");
};
connection.onerror = function (error) {
alert("something went wrong with your server " + error);
};
connection.onclose = function () {
alert("server had shut down now ");
};
connection.onmessage = function (message) {
try {
var json = JSON.parse(message.data);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ', message.data);
return;
}
if (json.type === 'message') {
addMessage(json.data.text);
} else {
console.log('Hmm..., I\'ve never seen JSON like this: ', json);
}
};
function addMessage(message) {
var rec_object = message;
var regexp1 = /[\/a-zA-Z]+(.jpg)/;
var regexp2 = /[\/a-zA-Z]+(.mp3)/;
var regexp3 = /[\/a-zA-Z]+(.mp4)/;
if (regexp1.test(rec_object)) {
document.write("<img width=\"300\" height=\"250\" src=\"" + rec_object + "\" \/>")
document.write("<br /><br /><br /><br /><br /><br /><br /><br />");
} else
if (regexp2.test(rec_object)) {
document.write("<audio controls>");
document.write("<source src=\"" + rec_object + "\"type=audio\/mpeg \/>");
document.write("</audio>");
document.write("<br /><br /><br /><br /><br /><br /><br /><br />");
} else
if (regexp3.test(rec_object)) {
document.write("<video width=\"300\" height=\"250\" controls>")
document.write("<source src=\"" + rec_object + "\"type=video\/mp4 \/>");
document.write("</video>");
} else
document.write(rec_object);
}
那么我怎么能不使用查询字符串呢?我只想将它从一个文件发送到另一个文件。我像上面一样尝试过,但我什么也没得到。