我一直在尝试使用jQuery Mobile向Web服务(用.NET编写)发送POST请求。我正在使用jQuery Mobile以及PhoneGap for iOS并在XCode中编写代码。
这是我正在运行的代码 -
var param = "{\"jsonText\": \"{ \"username\" : \"Test\", \"password\" : \"testing123\" } \"} ";
console.log(param)
$.ajax({
url: "https://example.asmx/authenticateUser",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data:JSON.stringify(param),
success: function(result){
console.log(result);
},
error: function(result){
console.log(result);
}
});
这给了我以下错误 -
{"readyState":4,"responseText":"{\"Message\":\"Cannot convert object of type \\u0027System.String\\u0027 to type
\\u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\\u0027\",\"StackTrace\":\" at
System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\\r\\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\\r\\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToType(Object o, Type type, 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.InvalidOperationException\"}","status":500,"statusText":"Internal Server Error"}
请帮忙。
答案 0 :(得分:1)
您想使用JSON.parse
而不是JSON.stringify
。前者从JSON字符串中获取对象(您拥有的)。后者将JavaScript结构转换为这样的字符串。
此外,您的JSON无效。 {
:
JSON.parse("{\"jsonText\": { \"username\" : \"Test\", \"password\" : \"testing123\" } } ")
答案 1 :(得分:1)
json的结果
"{\"jsonText\": \"{ \"username\" : \"Test\", \"password\" : \"testing123\" } \"} "
就是这样:
{
"jsonText": "{
"username": "Test",
"password": "testing123"
}"
}
那是错的,应该是:
{
"jsonText":{
"username": "Test",
"password": "testing123"
}
}
等效的json:
"{\"jsonText\":{\"username\":\"Test\", \"password\":\"testing123\"}}"
或者因为你传递的是一个对象,所以它必须是:
{
"username": "Test",
"password": "testing123"
}
等效的json:
{\"username\":\"Test\",\"password\":\"testing123\"}
请记住,您不必在""
花括号之间添加}
引号。