简体   繁体   English

使用JavaScript在Rails应用中通过POST发送富文本

[英]Sending rich text over POST in rails app using Javascript

I have in APP A the following rich text: 我在APP A中有以下富文本:

A nice basketball 一个不错的篮球

  • because I say so 因为我这么说
  • because my mother says so 因为我妈妈这么说
  • because my dog says so 因为我的狗这么说

In index.html.erb this rich text is accessible through product.body_html , which I load into a Javascript object called myProduct : 在index.html.erb中,可以通过product.body_html访问此富文本,我将其加载到名为myProduct的Javascript对象中:

var myProduct= new Object(); 
myProduct.desc ='<%= JSON.generate(raw(product.body_html), quirks_mode: true) %>';

Then I send this object via POST to my API in APP B using Javascript: 然后,我使用Javascript通过POST将对象发送到APP B中的API:

var url = appBURL + "/myapi/method";
  $.ajax({
      type: "POST",
      url: url,
      data: JSON.stringify(myProduct),
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(data){
        // data.desc should contain the same rich text
        $(".myDiv").html(data.desc);
      }
  });

And I get an answer back data.desc in app A that should contain the same rich text. 我得到了应答A中包含相同的富文本格式的data.desc的答案。 But when I display data.desc inside a <div> what I see printed on the screen is this 但是当我在<div>显示data.desc时,我在屏幕上看到的是

"<p>A nice basketball</p> <ul> <li>because I say so</li> <li>because my mother says so</li> <li>because my dog says so</li> </ul>" 

And what I'm actually inserting in that <div> (ie, the contents of data.desc ) is this 我实际上要在该<div>插入的内容(即data.desc的内容)是这个

"&lt;p&gt;A nice basketball&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;because I say so&lt;/li&gt;
&lt;li&gt;because my mother says so&lt;/li&gt;
&lt;li&gt;kjh&lt;/li&gt;
&lt;/ul&gt;"

The client in APP A is adding these quotes. APP A中的客户端正在添加这些引号。 Why? 为什么?

If I add in APP A the description like this: 如果我在APP A中添加如下描述:

myProduct.desc ='<%= raw(product.body_html) %>';

Then it works with normal text (and it doesn't add the quotes), but as soon as I have rich text it produces a syntax error when running the javascript. 然后,它可以与普通文本一起使用(并且不添加引号),但是一旦我具有富文本格式,则在运行javascript时就会产生语法错误。

当您在APP B中渲染文本时,请按以下方式渲染:

(CGI::unescapeHTML data.desc).html_safe

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

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