在 javascript 中格式化字符串

Formatting string in javascript

本文关键字:字符串 格式化 javascript      更新时间:2023-09-26

我正在对一个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

您可以使用此函数去除斜杠:http://phpjs.org/functions/stripslashes:537

您可以将 ''r' 替换为此函数:http://phpjs.org/functions/nl2br:480

您的服务器正在发送 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。