jquery Ajax不发送JSON数据

时间:2016-10-22 23:47:46

标签: javascript jquery json ajax

我正在尝试发送ajax发送请求,但它总是进入error

$('form#contactForm button.submit').click(function () {

            var contactName = $('#contactForm #contactName').val();
            var contactEmail = $('#contactForm #contactEmail').val();
            var contactSubject = $('#contactForm #contactSubject').val();
            var contactMessage = $('#contactForm #contactMessage').val();

            var data = {
                'contactName': contactName,
                'contactEmail': contactEmail,
                'contactSubject': contactSubject,
                'contactMessage': contactMessage
            };

            $.ajax({
                type: "POST",
                url: "/",
                data: data,
                dataType: 'json',
                contentType: "application/json",
                success: function (msg) {
                    alert('success message: ' + msg);
                    if (msg == 'OK') {
                        $('#image-loader').fadeOut();
                        $('#message-warning').hide();
                        $('#contactForm').fadeOut();
                        $('#message-success').fadeIn();
                        $('#contactForm button.submit').prop('disabled', true);
                    }
                    else {
                        $('#image-loader').fadeOut();
                        $('#message-warning').html(msg);
                        $('#message-warning').fadeIn();
                    }

                },
                error: function (err) {
                    if (contactName.length === 0 || contactEmail.length === 0 || contactSubject.length === 0 ||
                        contactMessage.length === 0) {
                        $('#message-warning').html('Please check form once again.');
                        $('#message-warning').fadeIn();
                        event.preventDefault();
                    }
                    alert('inside error: ' + err.message);
                }
            });
            return false;
});

这始终在alert('inside error: ' + err.message);中显示error。我也尝试了data: JSON.stringify(data),但它也没有效果。 data变量有问题吗?问题在哪里?

网络标签:

Request URL:http://localhost:3000/
Request Method:POST
Status Code:400 Bad Request
Remote Address:[::1]:3000
Response Headers
view source
Connection:keep-alive
Content-Length:24
Content-Type:text/html; charset=utf-8
Date:Sun, 23 Oct 2016 00:12:43 GMT
ETag:W/"18-9LwX+BuZqYnTTqGm6GcNuA"
X-Powered-By:Express
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:102
Content-Type:application/json
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
contactName=My+Name&contactEmail=email%40email.com&contactSubject=My+Subject&contactMessage=My+Message

后端帖子

router.post('/', function (req, res) {
    if (typeof req.body.contactName === 'undefined' || typeof req.body.contactEmail === 'undefined' ||
        typeof req.body.contactSubject === 'undefined' || typeof req.body.contactMessage === 'undefined' ||
        !validator.isEmail(req.body.contactEmail)) {
        return res.status(400).send('error');
    }
    mail.sendMail(req.body.contactName, req.body.contactEmail, req.body.contactSubject, req.body.contactMessage);
    return res.status(200).send('okay');
});

3 个答案:

答案 0 :(得分:0)

dataType是指服务器的预期响应 - 请参阅HERE。如果响应不是JSON,则从ajax函数中删除dataType: 'json',jQuery将进行智能猜测。

答案 1 :(得分:0)

我已删除dataType: 'json'contentType: "application/json"并且ajax请求已成功。我仍然不知道为什么,但删除它们后它才有效。

答案 2 :(得分:0)

ajax客户端希望您的响应MIME类型为' json',但是您提供了纯文本'好的'作为回应。

如果你仍然需要发送json作为回复,你可以使用res.type改变你的后端:

router.post('/', function (req, res) {
    if (typeof req.body.contactName === 'undefined' || typeof req.body.contactEmail === 'undefined' ||
        typeof req.body.contactSubject === 'undefined' || typeof req.body.contactMessage === 'undefined' ||
        !validator.isEmail(req.body.contactEmail)) {
        return res.status(400).type('json').send({"result": "error"});
    }
    mail.sendMail(req.body.contactName, req.body.contactEmail, req.body.contactSubject, req.body.contactMessage);
    return res.status(200).type('json').send({"result":"okay"});
});

然后你的前端应该按预期工作。对于大多数情况,您不需要指定dataType,因为ajax可以根据您的服务器响应自动确定mime类型。