<script type="text/javascript"> $(document).ready(function () { $("#btn").click(function () { var foobar = $(this).closest('#add-question').serializeArray(); $.ajax({ type: "POST",url: "/Services/QuestionsService.asmx/SubmitQuestion",data: "{foo:[" + JSON.stringify(foobar) + "]}",contentType: "application/json; charset=utf-8",dataType: "json",success: function (data) { $("#btn").text(data.d); } }); }); }); </script>
和服务:
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolBoxItem(false)] [System.Web.Script.Services.ScriptService] public class QuestionsService : System.Web.Services.WebService { [WebMethod] public string SubmitQuestion(string foo) { //do something with foo return "Message Sent"; } }
但是我在服务上遇到了500错误:
Request format is unrecognized for URL unexpectedly ending in ‘/SubmitQuestion’.
<system.web> <webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> </webServices> </system.web>
对于web.config,这似乎解决了第一个问题.但我现在在服务中得到一个错误,抱怨表单参数foo缺失但它已经明确提供了:
system.invalidOperationException: Missing parameter: foo.
at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
at System.Web.Services.Protocols.UrlParameterReader.Read(HttpRequest request)
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
有什么我想念的吗?
我认为这可能是serializeArray()的一个问题,因为如果我传入一个简单的json对象,它会点击web方法,例如:
var obj = { foo: 'bar' };
我是否错误地使用了serializeArray()?
以下是字符串化后的数据输出:
{ foo: [ [ { "name": "__EVENTTARGET","value": "" },{ "name": "__EVENTARGUMENT",{ "name": "__VIEWSTATE","value": "RHqOeKRh4e+2IZH9ZdPatwEklxypUzemNeDv7sO4l8vIR2TrECRFZvalrpbvVre0e6gkY9ZG3618dtU3BhYFW3YNn2y6VqeZlL5hmG/WplttZN8lhDkEl1bGOGWBsY52zVxWECkAC2hGtHwF5plmKsL3sHp3nFxh3yzWoGP1LwAc4sAZ/rgKvozqCp/4FfB6P4jBUQnL7Q5EkNsjWBntsXbUswC3cJpS22vgoJFHDh8Lm9n/VGzC86FUWipvGmOJ9/KVSlUBbJE3J0Fs6UZi+E6T1Ql+I8XBZlZOzDlbq40=" },{ "name": "ctl00$MainContent$txtName","value": "name field" },{ "name": "ctl00$MainContent$txtEmailAddress","value": "email address field" },{ "name": "ctl00$MainContent$txtLocation","value": "location field" },{ "name": "ctl00$MainContent$chkAnonymous","value": "on" },{ "name": "ctl00$MainContent$txtQuestion","value": "question field" },{ "name": "__EVENTVALIDATION","value": "ileV4/vPquayqiSQJEAvq1oHpIAkHN+fy4QhqOrQpp7NxE4z15rvbTH6BfaSCFFwt96JAp1aqQzuOFCTzc6KSEE6iWDmSDRcJWWOzyksSoXpAMBwLk3F6oAaWa4EIjEUb+2b/PJobySl5BaU3TG0JCZyHK2fxj5HXd8DG89gnmVXemTwq1Ax4BgJw1Z5z1uT8Sw7Xk6inUHAZ0NJH4QdTQ==" } ] ]
}
解决方法
[WebMethod] public string SubmitQuestion(object foo) { //do something with foo return "Message Sent"; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。