使用json_encode输出换行符或换行符? [英] Output line breaks or new lines with json_encode?

查看:844
本文介绍了使用json_encode输出换行符或换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JSON格式的新手,请原谅我缺乏知识。但不知何故,我需要在我的json_encode数组中添加一些换行符,以便它将使用多行进行解析。我搜索和搜索过,但没有任何东西适合我的情况。

I am new to JSON format so please forgive my lack of knowledge. But somehow, I need to add some line breaks to my json_encode array so that it will parse with multiple lines. I've searched and searched but nothing fits my situation.

输出为:

Following formats accepted: www.website.com website.com website.net/something

但是我想输出这样的数据:

But I'm looking to output the data like this:

Website needs to be in the following formats:  
www.website.com  
website.com  
website.net/something

我试过:

echo json_encode( 
    array( 'status' => 'failed',
           'message' => "Website needs to be in the following formats:\n
            www.website.com\n
            website.com\n
            website.net/something"
    ), JSON_PRETTY_PRINT);

但是Javascript将其解析为文字字符串,因此新行被忽略并输出。我可以使用直接JSON格式将数据从PHP发送到javascript,还是必须使用数组?

But Javascript is parsing it as a literal string so the newlines are ignored and outputted. Can I send the data from PHP to javascript using straight JSON format or do I have to use an array?

我也尝试过使用< ; br />

编辑:

我输出的方式如下:

EDIT :
I am outputting the following way:

$.ajax({
    url: "/forms/content_process.php",
    type:'POST',
    data: $(".content_cat").serialize(),
    processData: false,
    dataType: "json",
    success: function(response) {
        if (response.status == "failed") {
            $(".content_status").css( "background-color", "red" );
            $(".content_status").text(response.message).slideDown("normal");
        } else {
            $(".content_status").css( "background-color", "green" );
            $(".content_status").text("Your category was submitted!").slideDown("normal");
        }
    }
});


推荐答案

使用 \ n 将换行符添加到字符串中。也不要添加真正的换行符。

use \n to insert newline character into the string. don't add a real newline as well.

echo json_encode( 
    array( 'status' => 'failed',
           'message' => "Website needs to be in the following\nformats:\nwww.website.com\nwebsite.com\nwebsite.net/something"
    ), JSON_PRETTY_PRINT);

比将客户端插入dom之前客户端需要用<替换换行符code>< br /> 或使用 white-space:pre 。或者,您可以使用段落< p>< / p> 标记来围绕每一行。这样做看看: jQuery text()和换行符

than on the client side before inserting it into your dom, you will need to replace the newlines with <br /> or use white-space: pre. alternatively you could surround each line with paragraph <p></p> tags. to do so have a look here: jQuery text() and newlines.

这篇关于使用json_encode输出换行符或换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆