简体   繁体   中英

When to use document.write()?

I was told not to use document.write() by and SO member. That innerHTML is better, or better yet, manipulate the DOM directly.

However, If I'm loading a page for the first time and there is content that is stored on a mysql table, and hence it will be converted to HTML, how can I do this if I don't want the server doing this task?

If the server did it then I could just have PHP code generate the html and place it where needed..but bc I want Javasrcript(client) to render the HTML I use this code (which is generated by php, but less processing time, as it does not create the HTML)

 <script type='text/javascript'>document.write(Arc.ViewHBookmark('google.com|http://www.google.com|Google||ideeli.com|http://www.ideeli.com|Ideeli||kikin.com|http://www.kikin.com|Kikin||lot18.com|http://www.lot18.com|Lot18||twitter.com|http://twitter.com|Twitter'))</script>

This is how I have the client generate HTML on a page reload. Embedded Javascript with a document.write().

Is there a better way to do this? By better I mean a way that does not use document.write().

I can call a javascipt function that renders the HTML on the onload event, but how would I have access to the JSON data or similar(AML) in this case.

I could write it into the page..and then read it back in, generate the content, and write it back to the page...but this seems more inefficient than just using document.write()

Is it OK to use document.write() in this case?

If not, is writing structured data to the page and having javascript convert it to HTML considered good practice?

We don't know exactly what Arc.ViewHBookmark is supposed to do exactly, but it seems that it's returning HTML. So the answer is simple: make it manipulate the DOM directly (eg add elements dynamically) instead of having it return HTML strings. And then call it without wrapping it in document.write .

当然,使javascript对象保存您的数据库数据,然后根据javascript对象的构建方式呈现页面。

If I understand the question correctly, you can just use a div (or, depending on context, maybe span ) element with empty content where you now have the 'script` element, eg

<div id="foo"></div>

and then use JavaScript that puts the generated content into that element:

document.getElementById('foo').innerHTML = Arc.ViewHBookmark(...);

(You can put that eg into a script element that you place after the div element.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM