如何使用Javascript将数据发送到远程服务器 [英] How to send data to remote server using Javascript

查看:554
本文介绍了如何使用Javascript将数据发送到远程服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用javascript将数据发送到远程服务器。我该怎么做?

I need to send data to a remote server using javascript. How do I do this?

背景信息:
有一个网页,我用它从中提取一些信息,我需要将其发送回另一台服务器进行处理。回应不是必要的。数据是XML,我已对其进行URL编码。

Background info: There's a webpage from which I extract some information using JS, and I need to send it back to another server for processing. Response is not neccesary. The data is XML, Which I've URLencode'd.

如何做到这一点?

编辑

我请求数据的服务器与接收数据的服务器不同。只是为了澄清。

The server I'm requesting the data from is not the same that receives the data. Just to clarify.

推荐答案

最常见的方法之一是AJAX。以下是使用jQuery执行AJAX发布请求的方法:

One of the most common ways to do this is AJAX. Here's how you perform an AJAX post request using jQuery:

<script type="text/javascript">
  $.post('/remote-url', {xml: yourXMLString });
</script>

在服务器端,您可以像处理任何其他POST请求一样处理它。如果您使用的是PHP,那么 $ xml = $ _POST ['xml'];

On the server side you process it like any other POST request. If you're using PHP it's $xml = $_POST['xml'];

最大限制AJAX是您只允许向文档加载的同一域发出请求(也称为跨域策略)。有多种方法可以克服此限制,其中最简单的方法之一是 JSONP

The biggest limitation of AJAX is that you're only allowed to make requests to the same domain the document has been loaded from (aka cross-domain policy). There are various ways to overcome this limitation, one of the easiest one is JSONP.

UPD。对于跨域请求,一个非常简单(但不是通用)的解决方案是:

UPD. For cross-domain requests an extremely simple (though not universal) solution would be:

(new Image).src = 'http://example.com/save-xml?xml=' + escape(yourXMLString)

这将发出GET请求(在Internet Explorer中不能超过2KB)。如果您绝对需要POST请求或支持更大的请求主体,您可以在您的域上使用中间服务器端脚本,也可以将动态创建的html表单发布到iframe。

This will issue a GET request (which cannot exceed 2KB in Internet Explorer). If you absolutely need a POST request or support for larger request bodies you can either use an intermediate server-side script on your domain or you can post a dynamically created html form to iframe.

这篇关于如何使用Javascript将数据发送到远程服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆