Judy
Judy

Reputation: 1553

appending contents to a div element on loading a page using jquery

I want to append the html contents receiver back from the sever (server 2) to the body of the current page (which I received from sever 1). This I want to achieve while loading the page (received from server 1).( Hence I am getting the original contents from two different servers.)

I tried using

function Faulttest() {var myarray=new Array();
    var urlarray=new Array();
$(document).ready(function(){
    $.get({
     url:"http://csce.unl.edu:8080/Anomalies/index.jsp",
     data: "html",
     success:  function(result) {
     alert(result);
     $('#body').append(result) // result will be the contents received from the server
     },
     dataType:"text/html"
    });
});
// more contents   
}

The HTML contents of the page are:

<body style="font-size:62.5%;" onload="Faulttest();" >
<div id="body" >
        <h1>content top </h1>
       //HTML CONTENTS GOES HERE
</div>

Upvotes: 0

Views: 2544

Answers (2)

Shyju
Shyju

Reputation: 218732

It looks like you are trying to load a page from a different domain. Same Origin policy is going to give you trouble with that .You can't do that !

If the file you trying to load content from is in the same domain, you can do it easily by calling the jQuery get method.

$(function(){
  $.get("somepageInyourdomain.html",function(data){
       $('#body').append(data);
  });
});

Upvotes: 2

adeneo
adeneo

Reputation: 318192

I'm guessing you're confusing $.get and $.ajax, as you're using the syntax for $.ajax, and it should be:

$(document).ready(function(){

    Faulttest();

    function Faulttest() {
        var myarray=new Array();
        var urlarray=new Array();

        $.ajax({
            url:"http://csce.unl.edu:8080/Anomalies/index.jsp",
            data: "html",
            dataType:"text/html",
            success:  function(result) {
                $('#body').append(result);
            }
        });
    }
});

Also diEcho is right, normally you can't do a cross domain ajax request because of security limitations, but there are certain hacks. Using datatype jsonp will allow you to make cross domain requests, but then of course the service should return the result in json and support a callback etc.

And remove the onload function on the body tag, and run the function inside the document.ready statement to make sure jQuery is loaded.

Upvotes: 1

Related Questions