Javascript AJAX 可以从远程服务器请求数据吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3897641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can AJAX request data from a remote server?
提问by Francisc
Can I use XMLHttpRequests in JavaScript to request a file on a different server than the one from where the request was made?
我可以在 JavaScript 中使用 XMLHttpRequests 来请求与发出请求的服务器不同的服务器上的文件吗?
Thank you.
谢谢你。
回答by balexandre
You need to use a method that is called as JSONP.
您需要使用一种称为JSONP 的方法。
One of the best ways is to use jQuery to reduce the code and worries between your page and the server, and all you need to do is:
最好的方法之一是使用 jQuery 来减少您的页面和服务器之间的代码和烦恼,您需要做的就是:
$.ajax({
dataType: 'jsonp',
data: 'id=10',
jsonp: 'jsonp_callback',
url: 'http://myotherserver.com/getdata',
success: function () {
// do stuff
},
});
回答by BalusC
Only if the remote server supports JSONPor HTTP Access-Control
headers.
仅当远程服务器支持JSONP或HTTPAccess-Control
标头时。
PublicJSON API's (like the ones provided by Google.com, Facebook.com, etc) often do.
公共JSON API(如 Google.com、Facebook.com 等提供的 API)经常使用。