jquery TypeError:无法将对象转换为基元值

lf5gs5x2  于 12个月前  发布在  jQuery
关注(0)|答案(2)|浏览(80)

我有一个texteditor(div),里面有一个function来格式化(选定的)文本。当我标记文本的一部分并选择使其看起来像this(代码片段)时,我必须使用 来避免一些错误并使其用户友好。然而,这些数据被发送到服务器(nodeJS),它会导致一个错误,内容会分裂成一个对象,为了避免这个问题,我想在发送到服务器之前用一个空格替换 
我所做的是

// replace   by " "
let content = $('.editor').html().replace(/( )/gi, " ");

// replace editor html
$('.editor').html(content);

// print results
console.log("html: ",$('.editor').html());

在控制台中,它显示预期内容(文本:as <code>dasdasd</code>):

html:  as<span> </span><code>dasdasd</code><span> </span>

但是在服务器端,我得到了以下错误:

TypeError: Cannot convert object to primitive value

然后我决定打印包含编辑器内容的变量(这似乎很好?):

{ posterContent: 'as<span> </span><code>dasdasd</code><span> </span>' }

**问题:**如何将&nbsp;替换为空格,而无需将html转换为(string),以避免此错误?

bihw5rsg

bihw5rsg1#

我知道你解决了这个问题,但你可能有兴趣阅读这篇文章,因为你的问题来自于对web开发的一个误解,即数据编码。
据我所知,您不能将字符串&nbsp;传递到后端,因为它被解析为对象,所以我假设您使用GET或POST的application/x-www-form-urlencoded编码来发送请求。简单来说:

// this object
{
  a: 10,
  b: 20
}

// get passed to the server as this string
a=10&b=20

这很好。这是一个办法但是你必须处理发送特殊字符的正确编码,例如:

// you have this object:
{
  a: 10,
  b: 'hello&world'
}

// you encode it naively to this
a=10&b=hello&nbsp;world

// the server understands this
{
  a: 10,
  b: 'hello',
  nbsp: ';world'
}

&产生了这个bug,因为它是一个特殊的字符,不会被当作字符串的一部分来处理。*即使你找到了一个技巧,不使用&nbsp,或者用一个空格代替它,你会认为你已经解决了这个问题,但是... * 几乎所有的Unicode字符都是特殊字符,需要进行编码,以免产生bug .
使用encodeURIComponent对字符串进行编码,或者使用不同的编码(例如JSON)对数据进行POST。我个人会使用像fetch这样的函数,它可以为你做所有的工作,并省去所有与编码相关的问题:

let data = {
  userId: 1,
  id: 1
}

fetch('https://jsonplaceholder.typicode.com/posts',{
  method: 'POST',
  data: JSON.stringify(data)
})
.then(resp => resp.json())
.then(json => console.log(json));
1wnzp6jl

1wnzp6jl2#

在react.js中,我最终在应用程序中设置了默认模式,

.then((module) => ({ default: module.Home }))

希望这能起作用.

相关问题