我用Jquery调用 WebService,通过fiddler来查看返回数据,上面老提示
{"Message":"无效的 JSON 基元: id。","StackTrace":" 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n 在 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n 在 System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n 在 System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n 在 System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
我服务端
namespace ApplicationModuleDemo.Service
{
/// <summary>
/// test 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class test : System.Web.Services.WebService
{
[WebMethod]
public IList<OrganizationInstitutionCommentsInfo> GetList(int id)
{
IList<OrganizationInstitutionCommentsInfo> list = new OrganizationInstitutionComments().GetBySQL("[institutionId]=" + id + " and [passed]=1");
foreach (OrganizationInstitutionCommentsInfo model in list)
{
model.UserPhoto = model.UserPhoto.Replace("./", AppConfig.API_SERVER + "/");
model.UserUrl = AppConfig.API_SERVER + "/BlogManage/UserInfo.aspx?pkId=" + model.UserId;
model.Content = new PageBase().InitContent(model.Content);
}
return list;
}
}
}
客户端、
$.ajax({
type: "POST",
contentType: "application/json",
data: { id: id },
dataType: 'json',
url: "../Service/test.asmx/GetList", success: function(msg) {
alert(msg);
}
});
data的写法不对,要写成
data: '{ id: ' + id + ' }'
注意data必须是一个“表示JSON对象的字符串”,而不是一个“JSON”对象
原因是jquery会把JSON对象序列化成标准POST的形式,你此处的{ id: id }会变成形好id=3这样的形式,而ASP.NET WebService需要的是JSON格式的数据,所以必须把你的数据变成一个JSON样子的字符串