kristof_w
kristof_w

Reputation: 302

Formatting string in javascript

I'm doing a jQuery Ajax call to a PHP script that returns this string variable in Javascript:

"<div id=\"page\">\r\n\r\n\t"

I'm probably missing something simple here, but is there a way to revert \r\n to <br/>, but more importantly, reverting \"page\" to "page" ? I just can't figure it out.

Javascript looks like this:

    $.ajax({
        type: 'POST',
        dataType: "JSON",
        url:  sameURLasPHPscript,
        success:function(data){
            // successful request; do something with the data
            $('body').text(data);
        },
        error:function(){
            // failed request; give feedback to user
            alert('ErrorMessage');
        }
    });

My php file looks like this:

        $url = "someURL/controller/action/getID";

        $a = file_get_contents($url);           

        echo json_encode($a);

Edit : Solution can be found here: http://blog.dkferguson.com/index.cfm/2011/3/15/jQuery-Mobile-styling-loaded-content

Upvotes: 0

Views: 106

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272106

Your server is sending JSON encoded data, you should treat it likewise. Change the parameters of your jQuery.ajax so that it expects JSON data. jQuery will then parse the data and deal with all \", \r and \n.

Edit

Compare the output of these two jQuery functions:

$('body').text("<b>bold</b>"); // will write <b>bold</b> literally
$('body').html("<b>bold</b>"); // will write bold in bold font

You need to use jQuery.html function to display HTML as HTML.

Upvotes: 2

Jeroen
Jeroen

Reputation: 13257

You can strip the slashes using this function: http://phpjs.org/functions/stripslashes:537

And you can replace \r\n with this function: http://phpjs.org/functions/nl2br:480

Upvotes: 3

Related Questions