使用jquery无法从其他域获取iframe的值?

i have a example:

in domain 1: www.domain1.com/demo.php

<div id="result">Hello</div>

in domain 2: www.domain2.com/demo.php

jQuery(document).ready(function($) { 
   $('.click').click(function(){
      var value = $("a").attr("href");
      var dataString = 'var='+value;
      var url = 'http://www.domain1.com/test.php?'+dataString;
      $.getJSON(url + "&jsoncallback=?", function(data){
         $("#result").html(data);
      })
      return false;
   });  
});

<iframe src="http://www.domain1.com/demo.php" frameborder="0" border="0" scrolling="no"></iframe>
<a href="play" class="click">Click on this</a>

And finally www.domain1.com/test.php I call json callback:

<?php
if($_GET['var']) {
    $value = $_GET['var'];
    echo $_GET["jsoncallback"] . '(' . json_encode($value) . ');';
}
?>

=> I can't get value from domain 1 to domain 2 ?

After test, I run www.domain2.com/demo.php is result not show

The reason for this is that the browser will block the request for security reasons. This could allow a site to load another in the background using your current login, and then steal private information.

For instance, I log into my bank account and view my credit card, then I visit "imavirus.com" in another tab and it loads a hidden iframe to my bank. As I'm logged in in the bank site it will load logged in, and show my credit card information. (This may be a bad example because banks usually have better security, but you get the idea)

Try it in Chrome and you'll see a little red error pop up in the "Inspect Element" window. (Other browsers probably have similar)

That's cross domain issue you are facing. Why not spend a bit of your time taking a look at this tutorial?

Also, if you search on SO, there's a good post for you to reference as well.

If you've got access to the code on the domain you're accessing from the iFrame, you could try add this header:

// In PHP, before any output is sent...
header( "Access-Control-Allow-Origin: http://www.domain2.com" );

This will allow your AJAX request to return the result.

For security reason, you can't access cross-domain iframe directly.

But there are some solutions.

Look at this great example : http://onlineaspect.com/uploads/postmessage/parent.html in this post: http://onlineaspect.com/2010/01/15/backwards-compatible-postmessage/