还在纠结使用XMLHTTPRequest跨域 [英] Still confused about using XMLHTTPRequest cross domain

查看:35
本文介绍了还在纠结使用XMLHTTPRequest跨域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将数据 POST 到不同域中的服务器.该服务器正在使用 SSL,并希望数据采用 JSON 字符串的形式.我正在尝试通过 javascript 执行此操作.

I need to POST data to a server in a different domain. That server is using SSL and expects the data to be in the form of a JSON string. I am attempting to do this from javascript.

我创建数据并使用 JSON.stringify() 将其转换为正确的格式.然后我按如下方式发送:

I create the data and use JSON.stringify() to get it into the correct format. Then I send it as follows:

var url = "https://api.postageapp.com/v.1.0/send_message.json";

http=new XMLHttpRequest();
http.open("POST", url, true);

http.setRequestHeader("Content-type", "application/json");
http.setRequestHeader("Connection", "close");

// create the data in a data structure named post_data
var JSONText = JSON.stringify(post_data);
http.send(JSONText);

进行数据包跟踪我看到我的客户端与服务器进行了握手,但随后服务器两次回复加密警报",包括上次发回数据包的时间.浏览器调试器始终显示 405 - Method Now Allowed 错误.

Doing a packet trace I see my client do a handshake with the server but then twice the server replies with "Encrypted alert" including the last time it sends a packet back. The browser debugger always shows a 405 - Method Now Allowed error.

我缺少什么才能让它发挥作用?当他们在自己的域内尝试时,它运行良好.

What am I missing to get this to work? When they try it within their domain it runs fine.

推荐答案

您需要服务器返回这样的 HTTP 标头:

You need server to return a HTTP Header like that:

header('Access-Control-Allow-Origin: *');

现场示例:制作使用 XMLHttpRequest 或 XDomainRequest 的跨域 JavaScript 请求

这篇关于还在纠结使用XMLHTTPRequest跨域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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