我试图将数据POST到REST api而不使用
AJAX.我想以
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(); }
解决方法
您可以添加一个隐藏的输入字段与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