Synchronous cross sub-domain POST request with jQuery

前端 未结 3 1998
借酒劲吻你
借酒劲吻你 2021-01-06 00:59

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 resear

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-06 01:45

    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:

    • 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

    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!

提交回复
热议问题