使用Javascript触发事件发送HTTP Post

时间:2013-02-14 11:10:12

标签: javascript http post

我对javascript很陌生,正在研究一种通过IP解码视频的嵌入式系统。

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

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

任何熟悉此类事情的人都可以快速了解如何将帖子发送到已知的收听设备/位置并在其中包含数据?

非常感谢

1 个答案:

答案 0 :(得分:32)

如果您的Javascript引擎支持XMLHttpRequest(XHR),这很容易,这在网络上无处不在。谷歌或查看this page了解详情。我在下面提供了一个代码段。仔细阅读,特别是关于“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);