我正在尝试不使用AJAX将数据发布到REST api。我想以JSON格式发送数据。我有以下代码,但一直试图找出如何转换输入字段并将其发布到服务器。这是我的代码尝试:
<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
json