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);?
유효한 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)
위의 상황에서 효과가 있었을 것입니다.
참고 : 모든 브라우저가 해당 JSON 객체 (IE7-)를 지원하지 않는 json2.js 라이브러리를 추가해야합니다.
json.js와 json2.js의 차이점
답변
지터에서 언급했듯이이 $.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"
....
});
답변
다음과 같이 작동합니다.
data: JSON.stringify({'id':x}),
답변
Jquery Ajax는 기본적으로 다음과 같은 쿼리 문자열 매개 변수 형식으로 데이터를 보냅니다.
RecordId=456&UserId=123
processData
옵션이 false로 설정되어 있지 않으면 서버에 개체로 전송됩니다.
-
contentType
옵션은 형식 클라이언트가 데이터를 보낸 서버용입니다. -
dataType
옵션은 서버에서 어떤 유형의 데이터 클라이언트가 기대하고 있는지 알려주는 서버용입니다.
서버가 json이 아닌 쿼리 문자열 매개 변수로 구문 분석하도록 contentType을 지정하지 마십시오.
또는
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");
}
});
여기 문자열 유형 매개 변수에 대해 문자열 값으로 표시하기 위해 (\ ‘) 이스케이프 시퀀스 문자를 사용했습니다.
