开发者

Cross Site AJAX Request

开发者 https://www.devze.com 2023-01-26 09:58 出处:网络
What I am exactly trying to build is, an INTERFACE through which a user can send post request to my site and display the response on his browser.

What I am exactly trying to build is, an INTERFACE through which a user can send post request to my site and display the response on his browser.

For example

$.post(
     'http://www.mysite.com开发者_如何学Python/thirdpartyrequest.php',
     { param1: value1, param2: value2 },
     function(data) {
         $("#universalid").html(data);//Update with the response
     }
);
//however it is not allowed.

Any Idea how to do such Cross Site Ajax Request


Your best bet is to use JSONP. Check out:

http://api.jquery.com/jQuery.getJSON/

http://en.wikipedia.org/wiki/JSON

If you have a server providing data such as:

http://my.server.com/somedata.json

{
   'some': ['fancy', 'json' ],
   'structure: 'here'
}

You turn this into jsonp by providing a callback parameter in the request url - the de facto standard name for it is callback. Then on the server, you need to check this parameter and wrap your result in that callback (effectively turning it into javascript instead of json).

http://my.server.com/somedata.json?callback=receive_this

receive_this({
   'some': ['fancy', 'json' ],
   'structure: 'here'
});

(For the niggly, the response mime type for json should be application/json whilst for jsonp it should be application/javascript)

The client will now (conceptually) load the json like this:

<script type="text/javascript">

   var receive_this = function(json) {

     // do some stuff with data here.

   };

</script>

<script type="text/javascript" src="http://my.server.com/somedata.json?callback=receive_this"></script>

In practice you use something like jQuery to dynamically insert the jsonp request script tag into the DOM. jQuery defaults to calling the callback request parameter callback.

$.ajax({
  url: 'http://my.server.com/somedata.json',
  dataType: 'jsonp',
  success: receive_this
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号