Post form to an API with javascript and jquery

巧了我就是萌 提交于 2019-12-12 02:34:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!