开发者

Ajax response with newlines for textarea

开发者 https://www.devze.com 2023-02-06 09:49 出处:网络
I have a problem concerning an ajax-request that should return a string from the server with newlines (\\n) to fill the textarea.

I have a problem concerning an ajax-request that should return a string from the server with newlines (\n) to fill the textarea.

When I do the following just with javascript, it works and shows 2 lines in the textarea:

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 ch开发者_开发知识库aracters of the String and there's just one line

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?


Don't use .innerHTML = "Line1\nLine2". Use .value = "Line1\nLine2" instead.

value is for form values. You are not setting HTML contents here.


@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.

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:

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. But this is a way to solve that.

Any better suggestions are welcome :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消