append php in jquery

2019-07-24 05:23发布

问题:

I'm trying to dynamically create a div to show error messages using jquery. I'm able to use append() to create the HTML easily enough, but I need to call a php variable in order to display the content. If I just try adding php opening and closing tags like I would ordinarily, the append method doesn't behave as expected and outputs a seemingly random section from the middle of the line. How can I overcome this problem?

Here's the jquery code as I have it:

$(document).ready(function() {
    var errors_php = "<?php  echo validation_errors('<li>','</li>'); ?>";
    $('#wrapper').append("<div id='errors'><ul>"+errors_php+"</ul></div>");
    $('#errors').slideDown('slow');
});

Note: the validation_errors() function is a codeigniter method. Incidentally, if I remove the errors_php variable from the append() it works as expected, displaying an empty div.

EDIT:

The generated code is:

<div id="errors"><ul>',''); ?&gt;</ul></div>

回答1:

As per your comment:

I just looked up that question and it is exactly what I'm trying to do. Unfortunately, I don't understand from the answers how they've solved it. I've never used json data before. Where should I put that piece of code?

JSON data is simply JavaScript Object Notation, so if you set a JavaScript a variable to a JSON value it will essentially recreate a copy of the object that was serialized into JSON in the first place.

var errors_php = "<?php  echo validation_errors('<li>','</li>'); ?>";

should be:

var errors_php = <?php echo json_encode(validation_errors('<li>','</li>')); ?>;


回答2:

Make sure that the output from the PHP is properly escaped. If you have a quotation mark (") in the error code it will cause problems. Try wrapping validation_errors with addslashes:

$(document).ready(function() {
    var errors_php = "<?php echo addslashes(validation_errors('<li>','</li>')); ?>";
    $('#wrapper').append("<div id='errors'><ul>"+errors_php+"</ul></div>");
    $('#errors').slideDown('slow');
});