XMLHttpRequest 无法使用 jQuery 加载 URL [英] XMLHttpRequest cannot load an URL with jQuery
问题描述
我正在尝试从远程"网站获取一些 json 数据.我在 99000 端口上运行我的 Web 服务,然后在 99001 端口 (http://localhost:99001/index.html) 上启动我的网站.
I'm trying to get some json data from a "remote" website. I run my web service on the 99000 port then, I launch my website on the 99001 port (http://localhost:99001/index.html).
我收到以下消息:
XMLHttpRequest cannot load http://localhost:99000/Services.svc/ReturnPersons. Origin http://localhost:99001 is not allowed by Access-Control-Allow-Origin.
即使我以 HTML 文件的形式启动我的网页,我也会得到这个:
Even If I launch my web page as an HTML file, I get this:
XMLHttpRequest cannot load http://localhost:99000/Services.svc/ReturnPersons.Origin null is not allowed by Access-Control-Allow-Origin.
Web 服务返回数据.我尝试捕捉这样的数据项:
The web service returns data. I try to catch the data items like this:
var url = "http://localhost:99000/Services.svc/ReturnPersons";
$.getJSON(url, function (data) {
success: readData(data)
});
function readData(data) {
alert(data[0].FirstName);
}
我正在尝试获得这种结构:
And I'm trying to get this structure:
[{"FirstName":"Foo","LastName":"Bar"},{"Hello":"Foo","LastName":"World"}]
你知道我为什么会收到这个错误吗?
Do you know why I'm getting this error?
推荐答案
你不能做一个 XMLHttpRequest 跨域,唯一的选项"是一种叫做 JSONP 的技术,归结为:
You can't do a XMLHttpRequest crossdomain, the only "option" would be a technique called JSONP, which comes down to this:
开始请求:添加一个带有远程 url 的新 标记,然后确保远程 url 返回一个有效的 javascript 文件来调用您的回调函数.一些服务支持这一点(并让您在 GET 参数中命名您的回调).
To start request: Add a new <script>
tag with the remote url, and then make sure that remote url returns a valid javascript file that calls your callback function. Some services support this (and let you name your callback in a GET parameters).
另一种简单的方法是在您的本地服务器上创建一个代理",它获取远程请求,然后将其转发"回您的 javascript.
The other easy way out, would be to create a "proxy" on your local server, which gets the remote request and then just "forwards" it back to your javascript.
编辑/添加:
我看到 jQuery 内置了对 JSONP 的支持,通过检查 URL 是否包含callback=?"(jQuery 将在哪里替换 ? 与实际的回调方法).但是您仍然需要在远程服务器上处理它以生成有效的响应.
I see jQuery has built-in support for JSONP, by checking if the URL contains "callback=?" (where jQuery will replace ? with the actual callback method). But you'd still need to process that on the remote server to generate a valid response.
这篇关于XMLHttpRequest 无法使用 jQuery 加载 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!