真是痛苦!我试图从JavaScript调用Web服务,但我似乎无法找到使其工作所需的魔法酱。使用JSON从jQuery调用Web服务
我的代码看起来是这样的:
的JavaScript:
$.ajax({
url: "/Services/CompanyContactServices.asmx/AddContact",
type: 'POST',
contentType: "application/json",
dataType: "json",
data: {
companyId: 3725, firstName: firstName, lastName: lastName, email: email
},
success: function (data) {
alert('Success!');
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Web服务(asmx.cs):
[WebService(Namespace = CompanyListServices.XmlnsNamespace)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class CompanyContactServices : System.Web.Services.WebService
{
public const string XmlnsNamespace = "mynamespace";
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string AddContact(int companyId, string firstName, string lastName, string email)
{
return new JavaScriptSerializer().Serialize(0);
}
}
断点处开始我AddContact
方法永远不会到达。
error
的处理程序为我ajax()
调用包含在jqXHR
以下错误消息:
{消息 “:” 无效JSON原始:companyId “ ”堆栈跟踪。“:” 在System.Web.Script .Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() 在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(深度Int) 在System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(字符串输入,的Int32 depthLimit,JavaScriptSerializer串行器) 在System.Web.Scrip t.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上下文,JavaScriptSerializer序列化程序) 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”}”
铬报告以下网络数据:
请求URL:... /服务/ CompanyContactServices.asmx /的addContact
请求方法:POST
状态代码:500内部服务器错误
任何人都可以看到我是什么失踪?
[?这是同样的问题(http://stackoverflow.com/questions/2445874/messageinvalid-json-primitive-recordid) – Blazemonger
你可能要考虑的ASP .NET Web-API让后端更容易。当然,如果你喜欢对你的web方法中的json序列化和东西进行微管理,你可以坚持使用旧的技术... – Mithon