tags:

views:

108

answers:

2

Say,how to implement these three steps:

1.fetch a html source from server side

2.use the above source to create a DIV

3.append it to <body> Element

A: 

add a with class name to end of body say "append" with nothing in it.

then

$('.append').load('url of content');

Kindness,

Dan

Daniel Elliott
What does $('.append') mean in your code?
Shore
That's the element's classname to which jQuery will append the loaded file.
David Thomas
I don't want to put it in html before using it,how to create the element on the fly?
Shore
+6  A: 
$('<div></div>').load("/url/to/load.html").appendTo('body');

will create a div on the fly then make an ajax call (this must be a local file here), then append it to your body.

Additionnaly you can give your div more attributes :

$('<div class="cssname"><span>hello</span></div>')

Plus, you can also specifies a certain div of your page to load :

$('<div></div>').load("/url/to/load.html #onlythis .block")

There's no limit and keep in mind that if you want to create something that don't exist in your page, just do :

$('<element></element>')

and don't forget to append it

HF !

vvo
+1 - great answer
Russ Cam
@Russ, agreed. Let's see if Shore actually *accepts* it... =/
David Thomas
How to directly append html to body?
Shore
I mean is this doable:$.load("/url/to/load.html").appendTo('body');
Shore
i don't know, just try it ! This will work i think.Also $('body').load('...'); will work but replacing all your code in body (so this is useless to do it in ajax !)$('<div></div>').load("/url/to/load.html").appendTo('body');is a better solution, since you html will be wrapped in a single <div>. And it's faster to append only one big <div> for jquery than to append multiple <div>'s <h1>'s etc...
vvo
At last,I need to give the DIV container a ID,so,before appending it,need to check if it's already in DOM,if so,just use it.How ?
Shore
var myDiv = $('#divId');if (myDiv[0]){myDiv.load("/url/to/load.html").appendTo('body');}else{myDiv = $('<div id="divId"></div>').load("/url/to/load.html").appendTo('body');}
vvo
Bad news!$.load("Views/chatBox.html").appendTo('body') is not working!TypeError: $.load is not a function
Shore
@Shore - you would need to use $.get for that and append the result to body. There is no $.load , as the load command expects an HTML element to append the result into. http://docs.jquery.com/Ajax
Russ Cam