简体   繁体   中英

Importing JS Module to be called On HTML Form Submit

I'm helping a friend with a project, which requires the use of HTML alone. I've only written in React when writing front end, so I've never understood the interactions between plain HTML and Javascript. Right now we have a sign up form that on submit needs to make a request to the back end. The request is written in a separate file, and I can't get it to call the file upon form submit.

HTML File:

 <head> <script src="./build/createUser.js"></script> </head> ... <form onsubmit="createUser()"> <input> <button type="submit">Sign Up</button> 

JS File before it gets built by browserify:

 const serviceRequest = require('../../packages/serviceRequest'); module.exports = function createUser (options, cb) { serviceRequest({ method: 'POST', uri: '/user/create', body: { email: options.email, password: options.password, studentName: options.name } }, function (err, resp, body) { if (err) { console.log(err); cb(err); } if (resp.statusCode >= 400) { console.log('Unexpected response from create user endpoint'); console.log(resp.statusCode); console.log(body); cb('Unexpected Response'); } cb(null, body); }); }; 

(I assume) the issue you are having is that the way you are managing your exports means that your form has no way to reference your function onSubmit . You're not having issues compiling your project right?

I have two options for you.

( ONE ) Bind an event listener (cleaner)

import serviceRequest from '../../packages/serviceRequest';
const createUser = (event, options) => {
    event.preventDefault(); // Prevent default action of form
    // serviceRequest() // Perform Logic
};
document.querySelector('form').addEventListener(createUser); // Or add a more specific selector

( TWO ) Add your function to global scope.

const createUser = (event, options) => {};
window.createUser = createUser;

If you're build pipeline was just concatenating all your javascript your const 's would be declared globally but browserify / babel will wrap everything in a closure.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM