使用jQuery的同步跨子域POST请求 [英] Synchronous cross sub-domain POST request with jQuery

查看:255
本文介绍了使用jQuery的同步跨子域POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试执行跨网域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.

我研究过getJSON,除了我需要POST而不是GET之外,它工作得很好。

I have researched getJSON, which works great except that I need to POST not GET.

有可能做到这一点吗?如果是不是,有人可以向我解释getJSON的工作原理,以及为什么我不能做POST替代。

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.

推荐答案

无法提出跨网域请求(GET / POST等)使用XMLHttpRequest(又名AJAX)。

You CANNOT make a cross-domain request (GET / POST / etc.) with an XMLHttpRequest (aka AJAX).

当服务器支持它时,可以做一个JSONP请求。 JSONP请求的工作方式如下:

What you can do, when the server supports it, is make a JSONP request. A JSONP request works as follows:


  • jQuery从您提供的回调函数中创建一个全局可访问的函数

  • 代替使用XMLHttpRequest(AJAX)来发出HTTP请求,jQuery会动态地将SCRIPT标记插入到DOM

  • 脚本标记的SRC是请求URL

  • jQuery在查询字符串中添加了一个回调参数,如下所示:example.com/someurl.js?callback=someDynamicallyGeneratedMethodName

  • 然后由SERVER通过将JSON结果作为参数传递给someDynamicallyGeneratedMethodName来返回JavaScript。

  • jQuery creates a globally accessible function out of the callback function you provide as an argument
  • Instead of using XMLHttpRequest (AJAX) to make the HTTP request, jQuery dynamically inserts a SCRIPT tag into the DOM
  • The SRC of the script tag is the request URL to which you are trying to communicate
  • jQuery adds a callback param to the query string like so: example.com/someurl.js?callback=someDynamicallyGeneratedMethodName
  • It is then up to the SERVER to return JavaScript that your client can use by passing the JSON result as an argument to someDynamicallyGeneratedMethodName

如果你没有控制你正在发布的服务器,那么你运气不好,JSONP不会做你很好。无论服务器返回什么,都会在SCRIPT标记中,如果格式不正确,很可能会抛出错误。

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.

有关这方面的更多信息,我建议您看看基本$ .ajax函数,而不是快捷方式。 (在Ajax下的jQuery文档中,对不起我不能发布更多链接)

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)

再次,如果你没有控制你正在发布的服务器,你可能希望在可能的情况下查看代理。否则,IFRAME可能是您唯一的选择。还有一种方法来实现这一点与SWF(闪存)对象。我已经尝试过,但他们是XMLHttpRequest对象的限制的解决方法。

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.

希望我可以帮助!

这篇关于使用jQuery的同步跨子域POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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