开发者

How to get cross domain request's response in javascript

开发者 https://www.devze.com 2023-03-06 03:01 出处:网络
I am making a cross domain request in javascript by dynamically adding a script and setting its src attribute to the domain that I need to make request to.

I am making a cross domain request in javascript by dynamically adding a script and setting its src attribute to the domain that I need to make request to. For reference: http://alvinabad.wordpress.com/2009/02/13/feb13/

Script code:

var script_id = null;
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', crossDomainURL);
script.se开发者_如何学PythontAttribute('id', 'script_id');

script_id = document.getElementById('script_id');
if (script_id) {
    document.getElementsByTagName('head')[0].removeChild(script_id);
}

Now, I need to parse the Response of this request. I have checked the Raw Response from fiddler. The data is there, but it's not in the dom. It starts like this:

<script type="text/javascript">
/* <![CDATA[ */
    if (top == self || parent != top || document.location.hostname != document.domain) 
    {  
        top.location.replace("http:\/\/www.facebook.com\/?gringotts_redir");}
/* ]]> */
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"**... then the rest

The page source shows the javascript embedded by me, how do I parse the data that's generated from that code.


The way this is generally done is to have the script response consist of a function call to a function already present on the page. The browser will not let your code "see" the contents of the imported script, however, for security reasons. The browser will run the script, however, so long as it's valid JavaScript code. In your case, the response is not valid JavaScript code. There can't be a <script> tag or any HTML markup — it must be pure JavaScript code, just like the contents of any other file imported with a <script> tag.


What your asking for is known as JSONP or "JSON with padding".

see: http://en.wikipedia.org/wiki/JSONP for more info.

0

精彩评论

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