Ajax not being called

2019-09-23 20:18发布

问题:

I wrote a little form in HTML with three textboxes. The idea is to create a "Contact me" form that is going to use the information submitted, by NodeMailer. However, my ajax function is not being called. To be more specific, the info is not being sent to "/time" where the NodeMailer is. Any "pointers" Thanks in advance! Heres my JS file:

$(document).ready(function(){
    $("#send").click(function(e){ 

        var name = $('input#name').val();
        var email = $('input#email').val();
        var message = $('textarea#message').val();

        $.ajax({
            url: "/time",
            type: "POST",
            dataType: 'json',
            data: {
                name: name,
                email: email,
                message: message
            },
            success: function() {
                // Success message
                $('#success').html("<div class='alert alert-success'>");
                $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-success')
                    .append("<strong>Your message has been sent. </strong>");
                $('#success > .alert-success')
                    .append('</div>');

                //clear all fields
                $('#contactForm').trigger("reset");
            },
            error: function() {
                // Fail message
                $('#success').html("<div class='alert alert-danger'>");
                $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                $('#success > .alert-danger').append('</div>');
                //clear all fields
                $('#contactForm').trigger("reset");
            }
        })

    }); 

}); 

回答1:

Try a specific filename instead of a folder. ie;

url: "/time/index.html",

Include any errors from the Dev Console (F12 in Browser) to helps us help you.



回答2:

You are missing a couple of things here -

1) Add a contentType: "application/json" to the ajax options.

2) Stringify your JSON:

  data: JSON.stringify({
            name: name,
            email: email,
            message: message
        }),

Also, just double check if parameters of your /time method are name, email and message respectively.