用jQuery同步跨子域POST请求
我正在尝试执行跨域 POST 请求,但遇到了(或两处)困难。
我无法在服务器上放置代理页面 - 所以这不是一个选项。
我研究了 getJSON,它效果很好,只是我需要 POST 而不是 GET。
可以这样做吗?如果不是,有人可以向我解释 getJSON 是如何工作的以及为什么我不能做出 POST 替代方案。
I'm trying to do a cross domain POST request and have hit a wall (or two).
I can't put a proxy page on the server - so that is not an option.
I have researched getJSON, which works great except that I need to POST not GET.
Is it possible to do this? If it is not, can someone explain to me how getJSON works and why I cannot make a POST alternative.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能使用 XMLHttpRequest(又名阿贾克斯)。
当服务器支持时,您可以做的是发出 JSONP 请求。 JSONP 请求的工作方式如下:
如果您无法控制要发布到的服务器,那么您就不走运了,JSONP 不会给您带来太大好处。服务器返回的任何内容都将位于 SCRIPT 标记中,如果格式不正确,很可能会抛出错误。
有关这方面的更多信息,我建议您查看基本 $.ajax 函数而不是快捷方式。 (在 Ajax 下的 jQuery 文档中。抱歉,我无法发布更多链接)
同样,如果您无法控制要发布到的服务器,则可能需要查看代理(如果可能)。否则,IFRAME 可能是您唯一的选择。还有一种方法可以使用 SWF (flash) 对象来实现此目的。我没有尝试过,但它们是解决 XMLHttpRequest 对象限制的方法。
希望我能帮忙!
You CANNOT make a cross-domain request (GET / POST / etc.) with an XMLHttpRequest (aka AJAX).
What you can do, when the server supports it, is make a JSONP request. A JSONP request works as follows:
If you have no control of the server that you are posting to, then you are out of luck, JSONP won't do you much good. Whatever the server returns will be in a SCRIPT tag, and will most likely throw an error if it isn't formatted correctly.
For more info on this, I suggest you look at the base $.ajax function instead of the shortcuts. (In the jQuery documentation under Ajax. Sorry I can't post more links)
Again, if you don't have control of the server you are posting to, you might want to look into a proxy if possible. Otherwise, an IFRAME may be your only other option. There is also a method to accomplish this with a SWF (flash) object. I have tried neither, but they are workarounds to the limitations of the XMLHttpRequest object.
Hope I could help!
您可以发布帖子,但您想要的是 JSONP 请求来解决跨域问题。本质上,您提供一个回调函数,请求作为脚本内容返回,并且使用请求中的 JSON 数据调用您的回调。您的服务器端脚本需要使用围绕 JSON 对象的回调函数将数据作为函数调用提供回来。
请参阅有关 post 函数的文档。
ASP.NET MVC 操作:
You can do a post, but what you want is a JSONP request to get around the cross domain issues. Essentially you provide a callback function and the request comes back as script content and your callback gets called with the JSON data from the request. Your server side script will need to provide the data back as a function call using the callback function wrapped around the JSON object.
See the documentation on the post function.
ASP.NET MVC action for this:
如果您想进行跨域 POST,那么最简单的解决方案是此处提供的解决方案马特奥.
这对我很有用
If you want to do Cross Domain POST then the easiest solution is the one provided here by Matteo.
It worked great for me