问题
Im not good with forms. How do you send a post form from an underscore.js template to an express.js API with javascript? I try with the .submit() but it doesnt work. Im using jQueryMObile so the form is inside a data-role page.
The route on server:
app.put('/users/:userId/spot/:spotId/add', spot.addUserSpot);
The form:
<form id="follow" method="put">
<input type="hidden" id="spot" value="<%= this.model._id %>">
<input type="hidden" id="user" value="<%= user %>">
<input type="submit" id="submitButton" value="Follow spot">
</form>
jQuery("#follow").on('submit', function(){
console.log("SUBMITTED");
var spot = jQuery("#user").attr("value");
var user = jQuery("#spot").attr("value");
jQuery("#follow").attr("action", "/users/"+user+"/spot"+spot+"/add");
alert(jQuery("#follow").attr("http://127.0.0.1:3000/users/"+user+"/spot/"+spot+"/add"));
});%>
回答1:
Most browsers do not support PUT, but express.js has a built-in solution. Just add a method override to your form:
<form id="follow" method="post">
<input type="hidden" name="_method" value="put" />
来源:https://stackoverflow.com/questions/18013299/post-form-to-an-api-with-javascript-and-jquery