使用Javascript触发事件发送HTTP Post

And*_*nry 12 javascript post http

我是javascript的新手,正在研究一种通过IP解码视频的嵌入式系统.

我已经编写了一个小应用程序,用于使用javascript设置和更改频道,并包含一个用于远程控制和事件处理程序的键处理程序,因此如果视频停止或网络中断,我可以采取某些操作或提供消息,但现在我也想要设置自动HTTP POST,当我更改频道以包含有关设备和当前正在播放的网址的某些数据时,会发送该POST.

这是一个运行busybox的小型嵌入式硬件设备,所以我不能使用Ajax或添加任何其他正常的Web技术,我只需要使用Javascript发送由我监控的事件触发的HTTP POST,所以我的第一个目标是成为能够按下按钮并发送该POST消息,然后计算出何时触发它.

熟悉这些事情的人可以快速概述如何将帖子发送到已知的听音设备/位置并在其中包含数据?

非常感谢

Wil*_*son 33

如果您的Javascript引擎支持XMLHttpRequest(XHR),这在Web上无处不在,这很容易.谷歌或查看此页面了解详情.我在下面提供了一个代码段.仔细阅读,特别是关于"async"的评论是真实的,关闭处理程序中的闭包.此外,就Javascript而言,此代码是超轻量级的,我希望它可以在任何现代硬件足迹上正常工作.

var url = "http://www.google.com/";
var method = "POST";
var postData = "Some data";

// You REALLY want shouldBeAsync = true.
// Otherwise, it'll block ALL execution waiting for server response.
var shouldBeAsync = true;

var request = new XMLHttpRequest();

// Before we send anything, we first have to say what we will do when the
// server responds. This seems backwards (say how we'll respond before we send
// the request? huh?), but that's how Javascript works.
// This function attached to the XMLHttpRequest "onload" property specifies how
// the HTTP response will be handled. 
request.onload = function () {

   // Because of javascript's fabulous closure concept, the XMLHttpRequest "request"
   // object declared above is available in this function even though this function
   // executes long after the request is sent and long after this function is
   // instantiated. This fact is CRUCIAL to the workings of XHR in ordinary
   // applications.

   // You can get all kinds of information about the HTTP response.
   var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
   var data = request.responseText; // Returned data, e.g., an HTML document.
}

request.open(method, url, shouldBeAsync);

request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// Or... request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
// Or... whatever

// Actually sends the request to the server.
request.send(postData);
Run Code Online (Sandbox Code Playgroud)

  • 我正在使用node.js,这在var request = new XMLHttpRequest()之前添加以下行后对我有用; var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; 您可能还想安装XMLHttpRequest $ npm install xmlhttprequest (3认同)