javascript - 使用 Javascript 触发事件发送 HTTP Post

标签 javascript http post

我是 javascript 的新手,正在开发一个通过 IP 解码视频的嵌入式系统。

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

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

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

非常感谢

最佳答案

如果您的 Javascript 引擎支持网络上无处不在的 XMLHttpRequest (XHR),这就很容易了。谷歌或查看this page了解详情。我在下面提供了一个代码片段。仔细阅读它,尤其是关于“异步”为真和响应处理程序中的闭包的评论。此外,就 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);

关于javascript - 使用 Javascript 触发事件发送 HTTP Post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14873443/

相关文章:

javascript - AJAX HTTP GET 请求必须触发两次才能工作

wcf - Remoting 和 Wcf 之间的 Http 请求数差异

java - 为什么我们会收到 HTTP 503 服务不可用的信息?

jquery - Internet Explorer中跨域POST请求ajax

Laravel - 限制用户的帖子数量

javascript - 什么是 xml dom 命名空间以及为什么某些 DOM 方法末尾有 NS?

javascript - 多边形选择 OpenLayers 3

javascript - 使用光线转换器从玩家的视野中获取交叉点坐标?

javascript - 如何在 jQuery 单击事件中显示不透明背景

php - 如何将 php 变量传递到新页面以从数据库中删除一行?