我试图将我的HTML表单数据转换为JSON对象,以便通过Ajax进行提交。 似乎"工作",但我没有得到我想要的JSON格式。它可能与
有关JSON.stringify($("#frm_login").serializeObject())
我得到的JSON输出是:
[{"name":"username","value":"mike"},{"name":"password","value":"test123"}]
但我真正想得到的JSON输出更简单,类似于:
{
"username":"mike",
"password":"test123"
}
下面是我简单的html和ajax代码:
<form id="frm_login" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" />
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" />
<input type="button" data-theme="b" name="btn_login" id="btn_login" value="Login">
</form>
我的ajax代码:
$(document).on('click', '#btn_login', function(){
var url = 'http://localhost/proto01/api/users/token';
$.ajax({
url: url, dataType: "json", async: true,
type: "POST",
headers: { Accept : "application/json; charset=utf-8", "Content-Type": "application/json; charset=utf-8" },
data: JSON.stringify($("#frm_login").serializeObject()),
success: function (result) {
alert("Success");
},
error: function (request,error) {
alert('Network error has occurred please try again!' + error);
}
});
});
答案 0 :(得分:1)
如果您要对其进行序列化,则应该执行data: $("#frm_login").serialize()
From this StackOverflow post(见第2,第3和第4篇帖子)
JQuery Serialize - 请记住,虽然通过序列化,您必须使用Request.Form
(.NET)访问控制器中的数据
否则,您可以自己创建
var model = {
'username': $.trim($('[name="username"]').val()),
...
...
};
$.ajax({
url: url, dataType: "json", async: true,
type: "POST",
headers: { Accept : "application/json; charset=utf-8", "Content-Type": "application/json; charset=utf-8" },
data: JSON.stringify(model),
processData: false,
success: function (result) {
alert("Success");
},
error: function (request,error) {
alert('Network error has occurred please try again!' + error);
}
});