Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
932 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 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...