0

I'm using jQuery load() method to load various elements from webpage in another domain. The script is as follows:

<script>
    $(function(){
        $("#a1").load("http://webpage.anotherdomain.com/ #another_a1");
        $("#img1").load("http://webpage.anotherdomain.com/ #another_img1");
        $("#span1").load("http://webpage.anotherdomain.com/ #another_span1");
    });
</script>

and HTML is as follows:

<div id="a1"></div>
<div id="img1"></div>
<div id="span1"></div>

so the result HTML is

<div id="a1">
    <a id="another_a1" href="a_relative_url.aspx">description</a>
</div>
<div id="img1">
    <img id="another_img1" src="img_relative_url.ashx">
</div>
<div id="span1">
    <span id="another_span1">content</span>
</div>

The problem is that the loaded a and img elements has relative urls so hyperlinks don't work properly and images don't show up. How can I fix this?


Edit: With your answers the problem is solved and the script is now as follows:

<script>
    $(function(){
        $("#a1").load("http://webpage.anotherdomain.com/ #another_a1"function(){
            $("#another_a1").attr("href",function(){
                return "http://webpage.anotherdomain.com/"+$("#another_a1").attr("href");
            });
        });
        $("#img1").load("http://webpage.anotherdomain.com/ #another_img1",function(){
            $("#another_img1").attr("src",function(){
                return "http://webpage.anotherdomain.com/"+$("#another_img1").attr("src");
            });
        });
        $("#span1").load("http://webpage.anotherdomain.com/ #another_span1");
    });
</script>
Marek
  • 1
  • 2

2 Answers2

0

You can modify the content of the element once it has been loaded using a callback function passed to load.

$("#span1").load("http://webpage.anotherdomain.com/ #another_span1",function(content) {
   //load was successful,
   //in this callback function, you can now access $('#span1').html() and modify it as you see fit.

   //do something to modify the content
   content = content.replace(...)

   //reset the content
   $('#span1').html(content);

});
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
0

If you do not have any control over the page you are loading, it may be a better idea to not include it on your webpage.

If you still want to do that you can use jQuery's attr() function (http://api.jquery.com/attr/). $("#another_img1").attr("src", [yourUrl]);

kalsowerus
  • 998
  • 8
  • 23