我试图在不使用AJAX的情况下将数据发布到REST API。我想以JSON格式发送数据。我有以下代码,但我试图弄清楚如何转换输入字段并将其POST到服务器。这是我的代码尝试:
<form id = "myform" method = "post">
id: <input type = "text" id = "user_id" name = "user_id">
data: <input type = "text" id = "user_data" name = "user_data">
<input type = "button" id = "submit" value = "submit" onClick='submitform()'>
</form>
<script language ="javascript" type = "text/javascript" >
function submitform()
{
var url = '/users/' + $('#user_id').val();
$('#myform').attr('action', url);
//
// I think I can use JSON.stringify({"userdata":$('#user_data').val()})
// to get the data into JSON format but how do I post it using js?
//
$("#myform").submit();
}
答案 0 :(得分:16)
您可以使用json值添加隐藏的输入字段,如下所示 -
function submitform() {
var url = '/users/' + $('#user_id').val();
$('#myform').attr('action', url);
var data = JSON.stringify({
"userdata": $('#user_data').val()
})
$('<input type="hidden" name="json"/>').val(data).appendTo('#myform');
$("#myform").submit();
}
您可以使用json
参数(隐藏输入名称)访问您的json