這是我的小代碼片斷,用於將請求消息發送到服務器並獲取響應並進行打印。這是一個Chrome插件,但事情是,如果任何onClick操作將在瀏覽器上發生,那麼它將獲取url並且必須發送到另一個JavaScript文件,然後這個JavaScript文件負責將url發送到node.js服務器將一個變量從一個JavaScript文件傳遞到另一個JavaScript文件
的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);
}
因此,如何能我做使用查詢字符串?我只想將它從一個文件發送到另一個文件。我像上面那樣試過,但是我沒有得到任何東西。
請在發貼之前至少[美化](http://jsbeautifier.org/)您的代碼...;) –