jQuery 从没有 AJAX 的表单发布 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17116532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:28:39  来源:igfitidea点击:

POST JSON Data from form without AJAX

jqueryjson

提问by user1884367

I am trying to POST data to a REST api without using AJAX. I want to send the data in JSON format. I have the following code but am stuck trying to figure out how to convert the input field and POST it to the server. Here is my code attempt:

我试图在不使用 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();
}

回答by Mohammad Adil

You can add a hidden input field with the json value, like this -

您可以使用 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();
}

You can access your json using jsonparameter (name of hidden input)

您可以使用json参数(隐藏输入的名称)访问您的 json