【发布时间】:2014-03-04 09:34:35
【问题描述】:
我正在尝试使用 serializeArray() 将一些表单值序列化为 json 对象,然后将表单值发布到服务中的 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()
我有什么遗漏吗?
我认为serializeArray() 可能存在问题,因为如果我传入一个简单的 json 对象,例如:
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=="
}
]
]
}
【问题讨论】:
-
$('#add-question').serializeArray()它的输出是什么? -
你应该
.serializeArray()你的表格。这是$('#add-question')你的表单ID吗? -
@Jai,是的,这是我的表格。我会将输出作为图像添加到问题中,而不是将其粘贴到此处。
-
不要使用
JSON.stringify(data)- 只需发布data: data -
@Archer 那是我尝试的第一件事
标签: c# jquery ajax json webmethod