Using JSON to Call Web Service from jQuery
多痛苦啊!我试着从javascript中调用一个Web服务,但是我似乎找不到让它工作所需的魔力。
我的代码如下所示:
JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $.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):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | [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); } } |
在我的
我的
{ Message":"Invalid JSON primitive: companyId.",
"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"}"
Chrome报告以下网络数据:
Request URL:.../Services/CompanyContactServices.asmx/AddContact
Request Method:POST
Status Code:500 Internal Server Error
有人能看到我丢失的东西吗?
1 | { companyId: 3725, firstName: firstName, lastName: lastName, email: email } |
上面的代码是一个javascript对象,而不是一个JSON。JSON是一个JavaScript对象的字符串表示。现代浏览器已经实现了
例子:
1 2 | var company = {companyId: 3725, firstName: firstName, lastName: lastName, email: email}; var json = JSON.stringify(company); |