Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

jquery - POST JSON Data from form without AJAX

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();
}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...