在javascript中格式化字符串

时间:2012-05-12 19:49:19

标签: php javascript jquery json

我正在对PHP脚本执行jQuery Ajax调用,该脚本在Javascript中返回此字符串变量:

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

我可能在这里遗漏了一些简单的内容,但有没有办法将\r\n还原为<br/>,但更重要的是,将\"page\"还原为"page"?我只是想不出来。

Javascript看起来像这样:

    $.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');
        }
    });

我的php文件如下所示:

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

        $a = file_get_contents($url);           

        echo json_encode($a);

编辑:可以在此处找到解决方案:http://blog.dkferguson.com/index.cfm/2011/3/15/jQuery-Mobile-styling-loaded-content

2 个答案:

答案 0 :(得分:3)

您可以使用此功能剥离斜杠: http://phpjs.org/functions/stripslashes:537

你可以用这个函数替换\ r \ n: http://phpjs.org/functions/nl2br:480

答案 1 :(得分:2)

您的服务器正在发送JSON编码数据,您应该同样对待它。更改jQuery.ajax的参数,以便它需要JSON数据。然后,jQuery将解析数据并处理所有\"\r\n

修改

比较这两个jQuery函数的输出:

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

您需要使用jQuery.html功能将HTML显示为HTML。