![](/img/trans.png)
[英]Message: Invalid JSON primitive: ajax jquery method with Webmethod
[英]“Invalid JSON primitive” in Ajax processing
我在来自 jQuery 的 ajax 调用中遇到错误。
这是我的 jQuery 函数:
function DeleteItem(RecordId, UId, XmlName, ItemType, UserProfileId) {
var obj = {
RecordId: RecordId,
UserId: UId,
UserProfileId: UserProfileId,
ItemType: ItemType,
FileName: XmlName
};
var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);
$.ajax({
type: "POST",
url: "EditUserProfile.aspx/DeleteRecord",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
if (msg.d != null) {
RefreshData(ItemType, msg.d);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error occured during deleting");
}
});
}
这是我的WebMethod
:
[WebMethod]
public static string DeleteRecord(Int64 RecordId, Int64 UserId, Int64 UserProfileId, string ItemType, string FileName) {
try {
string FilePath = HttpContext.Current.Server.MapPath(FileName);
XDocument xmldoc = XDocument.Load(FilePath);
XElement Xelm = xmldoc.Element("UserProfile");
XElement parentElement = Xelm.XPathSelectElement(ItemType + "/Fields");
(from BO in parentElement.Descendants("Record")
where BO.Element("Id").Attribute("value").Value == RecordId.ToString()
select BO).Remove();
XDocument xdoc = XDocument.Parse(Xelm.ToString(), LoadOptions.PreserveWhitespace);
xdoc.Save(FilePath);
UserInfoHandler obj = new UserInfoHandler();
return obj.GetHTML(UserId, UserProfileId, FileName, ItemType, RecordId, Xelm).ToString();
} catch (Exception ex) {
HandleException.LogError(ex, "EditUserProfile.aspx", "DeleteRecord");
}
return "success";
}
有人可以告诉我我的代码有什么问题吗?
我收到此错误:
{
"Message":"Invalid JSON primitive: RecordId.",
"StackTrace":"
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)
at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)
at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
"ExceptionType":"System.ArgumentException"
}
只是猜测变量json
包含什么之后
var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);?
如果它是一个像{"foo":"foovalue", "bar":"barvalue"}
这样的有效 json 对象{"foo":"foovalue", "bar":"barvalue"}
那么 jQuery 可能不会将它作为 json 数据发送,而是将它序列化为foor=foovalue&bar=barvalue
因此你得到错误"Invalid JSON primitive: foo"
尝试将数据设置为字符串
$.ajax({
...
data: '{"foo":"foovalue", "bar":"barvalue"}', //note the additional quotation marks
...
})
这样 jQuery 应该保留数据并将字符串按原样发送到服务器,这应该允许 ASP.NET 解析 json 服务器端。
使用
data : JSON.stringify(obj)
我相信在上述情况下会起作用。
注意:您应该添加 json2.js 库所有浏览器不支持该 JSON 对象 (IE7-) json.js 和 json2.js 之间的区别
它的工作原理是这样的
data: JSON.stringify({'id':x}),
正如 jitter 所指出的, $.ajax
函数将用作data
参数的任何对象/数组序列化为 url 编码格式。 奇怪的是, dataType
参数仅适用于来自服务器的响应 - 而不适用于请求中的任何数据。
遇到同样的问题后,我下载并使用jquery-json 插件将请求数据正确编码到 ScriptService。 然后,使用$.toJSON
函数对发送到服务器的所需参数进行编码:
$.ajax({
type: "POST",
url: "EditUserProfile.aspx/DeleteRecord",
data: $.toJSON(obj),
contentType: "application/json; charset=utf-8",
dataType: "json"
....
});
Jquery Ajax 将默认以查询字符串参数形式发送数据,例如:
RecordId=456&UserId=123
除非processData
选项设置为 false,在这种情况下,它将作为对象发送到服务器。
contentType
选项用于客户端发送数据的格式的服务器。
dataType
选项用于服务器,它告诉客户端期望从服务器返回什么类型的数据。
不要指定 contentType 以便服务器将它们解析为查询字符串参数而不是 json。
或者
使用 contentType 作为 'application/json; charset=utf-8' 并使用 JSON.stringify(object) 以便服务器能够从字符串反序列化 json。
我猜@jitter 的猜测是正确的,但他的解决方案对我不起作用。
这是它的工作原理:
$.ajax({
...
data: "{ intFoo: " + intFoo + " }",
...
});
我没试过,但我认为如果参数是一个字符串,它应该是这样的:
$.ajax({
...
data: "{ intFoo: " + intFoo + ", strBar: '" + strBar + "' }",
...
});
我遇到了同样的问题,我带来的好解决方案如下:
尝试这个...
$.ajax({
type: "POST",
url: "EditUserProfile.aspx/DeleteRecord",
data: '{RecordId: ' + RecordId + ', UserId: ' + UId + ', UserProfileId:' + UserProfileId + ', ItemType: \'' + ItemType + '\', FileName: '\' + XmlName + '\'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
if (msg.d != null) {
RefreshData(ItemType, msg.d);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error occured during deleting");
}
});
请注意这里的字符串类型参数,我使用 (\\') 转义序列字符将其表示为字符串值。
如果手动格式化 JSON,这里有一个非常方便的验证器: jsonlint.com
使用双引号代替单引号:
{
'project': 'a2ab6ef4-1a8c-40cd-b561-2112b6baffd6',
'franchise': '110bcca5-cc74-416a-9e2a-f90a8c5f63a0'
}
{
"project": "a2ab6ef4-1a8c-40cd-b561-2112b6baffd6",
"franchise": "18e899f6-dd71-41b7-8c45-5dc0919679ef"
}
这里dataTpe是“json”,所以,data/reqParam在调用API时必须是字符串的形式,你想要多少对象就多少,但最后在$.ajax的数据中对对象进行字符串化。
let person= { name: 'john',
age: 22
};
var personStr = JSON.stringify(person);
$.ajax({
url: "@Url.Action("METHOD", "CONTROLLER")",
type: "POST",
data: JSON.stringify( { param1: personStr } ),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
console.log("Success");
},
error: function (error) {
console.log("error found",error);
}
});
或者,
$.ajax({
url: "@Url.Action("METHOD", "CONTROLLER")",
type: "POST",
data: personStr,
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
console.log("Success");
},
error: function (error) {
console.log("error found",error);
}
});
我遇到过同样的问题。 我从弹出窗口关闭调用父页面“保存”。 发现我在具有相同控件 ID 的父页面和弹出页面上都使用ClientIDMode="Static"
。 从其中一个页面中删除ClientIDMode="Static"
解决了这个问题。
在服务器上,将 json 序列化/反序列化为自定义对象:
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
这些答案只是让我在无效参数和缺失参数之间来回跳动。
这对我有用,只需将字符串变量用引号括起来......
data: { RecordId: RecordId,
UserId: UId,
UserProfileId: UserProfileId,
ItemType: '"' + ItemType + '"',
FileName: '"' + XmlName + '"'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.