I have a script called at the end of an html page like this.
<body>
<script type="text/javascript">
$(document).ready(function() {
//define php info and make ajax call to recreate divs from XML data
$.ajax({
url: "get_nodes.php",
type: "POST",
data: { },
cache: false,
success: function (response) {
if (response != '')
{
alert(response);
}
}
});
});
</script>
</body>
The php script has echo statements that write javascript. The echo statements are not printed in the document. They are being sent somewhere, I don't know where. If I look at the response from the ajax call to php with the alert function, all the echo statements are printed in the alert box as I would expect them to be printed in the document itself.
My questions are:
- What does ajax do with the php echo statements?
- What is the way to have them printed in the document?
Here is the PHP file get_nodes.php called through ajax.
<?php
function get_nodes() {
// load SimpleXML
$nodes = new SimpleXMLElement('communities.xml', null, true);
foreach($nodes as $node) // loop through
{
echo "\n<script type='text/javascript'>\n";
echo " var newdiv = document.createElement('div');\n";
echo " newdiv.id = '".$node['ID']."';\n";
echo " newdiv.className ='comdiv ui-widget-content';\n";
echo " newdiv.style.top = '".$node->TOP."'\n";
echo " newdiv.style.left = '".$node->LEFT."';\n";
echo " newdiv.style.width = '".$node->WIDTH."';\n";
echo " newdiv.style.height = '".$node->HEIGHT."';\n";
echo " $( '#page' ).append(newdiv);\n";
echo " var heading = document.createElement('p');\n";
echo " heading.innerHTML = '".$nod开发者_如何学Goe->NAME."';\n";
echo " heading.className ='comhdr editableText ui-widget-header';\n";
echo " $('#".$node['ID']."').append(heading);\n";
echo " $('#".$node['ID']."').resizable();";
echo " $('#".$node['ID']."').draggable();";
echo " $('#".$node['ID']."').draggable('option', 'handle', '.comhdr');";
printf('$("#%s").append("<a href=\\"#\\" onClick=\\"delete_div(\'%s\');\\">Delete</a> ");', $node
['ID'], $node['ID']);
printf('$("#%s").append("<a href=\\"#\\" onClick=\\"add_url(\'%s\');\\">Add URL</a> ");', $node
['ID'], $node['ID']);
echo "\n</script>\n";
}
return;
}
echo get_nodes();
?>
As Incognito pointed out, your ajax call does not care about what your PHP function is doing - all that matters in this case is the content returned from the server, not how the content is created.
Try adding the dataType
option to your ajax call to specify a response type of script
, and use the append
or appendTo
function to add the script to the document body:
$.ajax({
url: "get_nodes.php",
type: "POST",
data: { },
dataType: 'script',
cache: false,
success: function (response) {
if (response != '')
{
$(document.body).append(response);
}
}
});
Also, a suggestion: In your server-side function, why not echo HTML markup instead of a javascript function which creates markup?
精彩评论