JQuery ajax multiline "script" answer

I am developing a template creation tool that uses a jQuery Ajax request that sends parameters to a PHP file. PHP really creates an HTML template.

// Send for processing. Expect JS back to execute.
function generate() {
$.ajax({
    type: "POST",
    url: "generate.php",
    data: $('#genform :input').serialize(),
    dataType: "script",
    beforeSend: function() {
        $("#loading").html("<img src='images/loadbar.gif' />");
        $("#loading")           
        .dialog({
            height: 80,
            width: 256,
            autoOpen: true,
            modal: true
        });
    },
    success: function(data) {
        $("#loading").dialog('close');
    }
});
}

My problem is that I have ajax dataType: set to "script". Using this, the PHP file generates some jQuery dialogs for any errors that work well. However, after I create the HTML, I am unable to pass it.

So, I probably have 100 lines of generated HTML and javascript that I would like to work with. In a PHP file, I tried:

echo('$("#result").html("'.$html.'");');

, $html . , Chrome "gen.html: 1 Uncaught SyntaxError: ILLEGAL". , , .

, , $html , :

$html = "<div>hi there</div>";

( - ). :

$html = "<div>
           hi there
         </div>";

.

, , . , HTML-.

PHP, , HTML-.

+3
4

( xml-) - JSON, . , , jQuery, JSON . :

  • dataType: "script" datatype: "json"
  • , html.
  • PHP, json_encode($html);

success: function(data) {
    $("#loading").dialog('close');
    $("#result").html(data.result_html);
}

PHP:

echo json_encode(array('result_html' => $html));

HTML- , JSON, $("#result").html(data); PHP echo json_encode($html);

+2

dataType "text" "xml", .

dataType: ($.browser.msie) ? "text" : "xml",
0

, javascript:

$html = str_replace (array ('\\', "\ r", "\n", ' "'), array ('\\\\', '\ r', '\n', '\" '), $html);

echo ('$ ("# result") HTML (. "' $ HTML .."); ');

0
source

Try creating an output handler function:

function ob_handler($string, $flags) {
    return nl2br($string);
}

Or:

function ob_handler($string, $flags) {
    $string = str_replace(array("\r", "\n"), array('', ''), $string);
    return $string;
}

And then use its code:

ob_start('ob_handler');
/// all your code here
ob_end_flush();
0
source

Source: https://habr.com/ru/post/1746228/


All Articles