多么痛苦!我正试图用JavaScript调用一个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);
}
});
网络服务(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
中包含以下错误消息:
{Message“:”无效的JSON原语:companyId。“, “StackTrace”:“在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() 在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32深度) 在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) 在System.Web.Script.Serialization.JavaScriptSerializer.Deserialize [T](字符串输入) 在System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext上下文,JavaScriptSerializer序列化程序) System.Web.Script.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData,HttpContext context)at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,WebServiceMethodData methodData)“,”ExceptionType“:”System.ArgumentException“} “
Chrome会报告以下网络数据:
请求网址:... / Services / CompanyContactServices.asmx / AddContact
请求方法:POST
状态代码:500内部服务器错误
有人能看到我错过的东西吗?
答案 0 :(得分:4)
{ companyId: 3725, firstName: firstName, lastName: lastName, email: email }
上面的代码是一个javascript对象,而不是JSON。 JSON是javascript对象的字符串表示。现代浏览器已实施json.stringify
,但如果您计划控制降级,则需要使用JSON3之类的填充。
示例:
var company = {companyId: 3725, firstName: firstName, lastName: lastName, email: email};
var json = JSON.stringify(company);