在不使用AJAX的情况下从表单发布JSON数据 [英] POST JSON Data from form without AJAX

查看:131
本文介绍了在不使用AJAX的情况下从表单发布JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试不使用AJAX将数据发布到REST api.我想以JSON格式发送数据.我有以下代码,但仍在尝试找出如何转换输入字段并将其发布到服务器的方法.这是我的代码尝试:

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:

<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值的隐藏输入字段,例如-

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

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

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

这篇关于在不使用AJAX的情况下从表单发布JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆