通过 API PUT 将文本区域保存到数据库,删除换行符

React textarea save to database via API PUT removing linebreaks

本文关键字:数据库 删除 换行符 保存 区域 API PUT 文本 通过      更新时间:2023-09-26

我正在使用$ajax将注释放入我的反应应用程序中的数据库中。注释从文本区域保存没有问题,并呈现在我的应用程序中 - 但没有换行符。

根据这个线程 https://github.com/ssorallen/turbo-react/issues/22 反应会故意删除换行符。前端有没有办法解决这个问题?

我已经尝试了几种不同的方法(其中大多数是这个版本的ReactJS - 多行文本区域(:用'''n替换'n;用br替换'n(不仅不起作用,而且当html br元素在文本区域中呈现时也很丑陋(;在PUT上使用encodeURI,在GET上使用decodeURI。这些尝试的解决方案导致我的 API PUT 请求出错,因为它无法保存编码 URI 中的特殊字符,并且'''n的反斜杠被视为正斜杠,从而导致 API 调用获得错误的搜索路径(如 api/comment/12312/Thisisa/nComment(。

该组件非常庞大,但这是文本区域渲染部分:

var resourceInputValue = this.state.resourceValue;
var commentInputValue = this.state.commentValue;

(...

<div className="detailsForms">
        <form>
          <textarea type="text" name="comment" className="commentForm" placeholder="Comment" defaultValue={commentInputValue} onChange={this.changeComment}/><img src="img/cancel.png" className="clearComment" onClick={this.clearComment}/>
        </form>
        <div className="formButtonDiv">
          <button className="formButton" type="button" onClick={this.putComment}>Add Comment</button>
        </div>
      </div>

和方法:

getInitialState: function(){
    return {
      commentValue: this.props.orderProps.comment
    }
  },
changeComment: function(event){
    this.setState({
      commentValue: event.target.value
    });
    if(event.target.value === "") {
      this.setState({
        commentValue: null
      });
    }
  },
  putComment: function(){
    $.ajax({
      type: "PUT",
      url: apiUrl + 'api/OrderComment/' + this.state.detailsId + "/" + this.state.commmentValue,
      beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", 'Bearer ' + token);
      },
      success: function () {
        document.getElementsByClassName("formButton")[1].className += " formButtonSuccess";
        document.getElementsByClassName("formButton")[1].innerHTML = "Done!";
        clearInterval(timer);
        ajaxCallOrders();
      },
      done: function(){
      }
    }).fail(function (_d) {
      document.getElementsByClassName("formButton")[1].className += " formButtonFail";
      document.getElementsByClassName("formButton")[1].innerHTML = "Try again";
    });
  },

尝试在发送文本之前运行 encodeURI(( 并在后端对其进行解码。