简体   繁体   English

Ajax响应,换行符为textarea

[英]Ajax response with newlines for textarea

I have a problem concerning an ajax-request that should return a string from the server with newlines (\\n) to fill the textarea. 我有一个有关ajax请求的问题,该请求应从服务器返回一个带有换行符(\\ n)的字符串以填充文本区域。

When I do the following just with javascript, it works and shows 2 lines in the textarea: 当我仅使用javascript执行以下操作时,它可以工作并在textarea中显示2行:

function fillTextArea(){
document.getElementById('myTextArea').innerHTML = "Line1\nLine2";
}

But if I get the value from the server using ajax, the \\n is treated like all the other characters of the String and there's just one line 但是,如果我使用ajax从服务器获取值,则\\ n会被视为String的所有其他字符,并且只有一行

function fillTextArea() {
new Ajax.Request("/myUrl/....",{
    asynchronous:true,
    evalScripts:true,
    onSuccess:function(transport){
        document.getElementById('myTextArea').innerHTML = transport.responseText;
    }
});
}

Does anybody know how to deal with newlines in the responseText of an ajax request? 有人知道如何处理ajax请求的responseText中的换行符吗?

Don't use .innerHTML = "Line1\\nLine2" . 不要使用.innerHTML = "Line1\\nLine2" Use .value = "Line1\\nLine2" instead. 使用.value = "Line1\\nLine2"

value is for form values. value是用于表单值。 You are not setting HTML contents here. 您未在此处设置HTML内容。

@Tomalak: The Ajax Function returns a String with the \\n like "Line1\\nLine2", but the textarea just shows one row with the whole String, so \\n is just also shown in the textarea as text instead of making a new line. @Tomalak:Ajax函数返回一个带有\\ n的字符串,例如“ Line1 \\ nLine2”,但是textarea仅显示包含整个String的一行,因此\\ n也在文本区域中显示为文本,而不是换行。

I've found a small workaround: 我发现了一个小解决方法:

If my ajax function returns "Line1NEWLINELine2" and it replaces "NEWLINE" with \\n, this works, so the function looks like that: 如果我的ajax函数返回“ Line1NEWLINELine2”,并用\\ n替换“ NEWLINE”,则此方法有效,因此该函数如下所示:

function fillTextArea() {
new Ajax.Request("/myUrl/....",{
    asynchronous:true,
    evalScripts:true,
    onSuccess:function(transport){
        var responseText = transport.responseText;
        var adjustedResponseText = responseText.replace(/NEWLINE/g, '\n');

        document.getElementById('myTextArea').value= adjustedResponseText;
    }
});
}

I am really not sure, why it makes a difference, if the value comes from a ajax request or just as a static string in the javascript function. 我真的不确定,如果值来自ajax请求还是javascript函数中的静态字符串,为什么会有所不同。 But this is a way to solve that. 但这是解决该问题的一种方法。

Any better suggestions are welcome :-) 任何更好的建议,欢迎:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM