我试图使用serializeArray()将某些表单值序列化为json对象,然后将表单值POST到服务中的WebMethod
。通过ajax调用将表单值传递给C#WebMethod
<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错误:
请求格式是无法识别的URL在 '/ SubmitQuestion' 意外结束。
我发现其中建议增加一个类似的问题:
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
到Web.config,这似乎解决了第一个问题。但我现在得到的服务抱怨的形式参数foo
丢失但它显然已经提供了一个错误:
System.InvalidOperationException:缺少参数:FOO。 在System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection中收集) 在System.Web.Services.Protocols.UrlParameterReader.Read(HttpRequest的请求) 在System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() 在System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
有什么我失踪了吗?
我觉得,因为它击中了网络法测得的,如果我在一个简单的JSON对象传递,例如它可能是与serializeArray()
一个问题:
var obj = { foo: 'bar' };
我使用serializeArray()
不正确?
这里是data
被字符串化后的输出:
{
foo: [
[
{
"name": "__EVENTTARGET",
"value": ""
},
{
"name": "__EVENTARGUMENT",
"value": ""
},
{
"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=="
}
]
]
}
'$(“#附加问题”)serializeArray()'什么是它的输出? – Jai
你应该'.serializeArray()'你的表格。这是'$('#add-question')'你的表单的ID吗? – Jai
@Jai,是的,这是我的形式。我会将输出添加为问题的图像,而不是将其粘贴到此处。 – DGibbs