我正在构建JSON对象,并使用JQuery ajax将其传递到服务器。
data: "{'authorID' : '" + authorID + "', 'title' : '" + encodeURIComponent(blogTitle) + "', 'msg' : '" + encodeURIComponent(blogBody) + "', 'preview' : '" + encodeURIComponent(mediaContent) + "', 'layoutID' : '" + previewLayoutId + "', 'threadID' : '" + threadID + "'}"
但是,当我的blogBody变量包含'代码时,将失败并显示错误消息:
'
{"Message":"Invalid object passed in, \u0027:\u0027 or \u0027}\u0027 expected. (107): {\u0027authorID\u0027 : \u0027148385\u0027, \u0027title\u0027 : \u0027123213\u0027, \u0027msg\u0027 : \u0027%3Cp%3Eqqq%3C%2Fp%3E%3Cp%3E%3Cbr%3E%3C%2Fp%3E%3Cp%3E\u0027\u0027\u0027\u0027%3C%2Fp%3E\u0027, \u0027preview\u0027 : \u0027\u0027, \u0027layoutID\u0027 : \u00271\u0027, \u0027threadID\u0027 : \u00270\u0027}","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
有人可以说错误在哪里以及如何解决?
在JSON中,键必须用双引号(")而不是单引号(')引起。同样,字符串值必须用双引号而不是单引号引起来。您正在使用单引号。例如,authorId标题文字前后。
"
authorId
因此,至少,您需要交换这些引号,例如:
data: '{"authorID" : "' + authorID + '", "title" : "' + encodeURIComponent(blogTitle) + '", "msg" : "' + encodeURIComponent(blogBody) + '", "preview" : "' + encodeURIComponent(mediaContent) + '", "layoutID" : "' + previewLayoutId + '", "threadID" : "' + threadID + '"}'