为什么AJAX + GET刷新页面?

时间:2018-08-03 01:51:47

标签: javascript ajax

我尝试了很多方法来防止这种情况,但没有任何工作令人困惑。

这是获取路线。

router.get('/some', function(request, response, next) {
    console.log('> info: some');
    response.send({"hello": "world"});
}

这是挂钩到元素的onClick的ajax部分。

  on_click = function(event) {
    //console.log(event.href);

    event = event || window.event;
    var target = event.target || event.srcElement;
    if (target.nodeType == 3)
        target = target.parentNode;

    target.preventDefault();
    target.stopPropagation();
    target.stopImmediatePropagation();

    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation();

   $.ajax({
            type: 'GET',
            url: target.href,
            dataType: 'json',
            cache: false
        })
        .done(function(received_data) {
            $('.container').html('<h1>hello here</h1>');
            return false;
        })
        .fail(function(xhr, status, error) {
            alert(xhr.responseText);
            return false;
        });
   return false;
}

我希望看到“你好,在这里”。它适用于小型测试程序。但是,当我添加到开发代码中时,它总是显示白页,其中包含hello world的json字符串。

到目前为止,我已经尝试了以下方法。

  • 直接发送字符串而不是JSON对象
  • 将dataType更改为文本
  • 将processData设置为false
  • preventDefault,stopPropagation,stopImmediatePropagation

我很抱歉不能上传开发代码,但是有人猜测为什么刷新页面如此固执吗?

顺便说一句,对于POST,它运行完美。

这是相关元素:

<a href="/some" onClick="on_click(this); return false;"></a>

1 个答案:

答案 0 :(得分:1)

代替

response.send({"hello": "world"});

尝试

response.json({"hello": "world"});

Express docs:https://expressjs.com/en/api.html#res.json

使用response.json()正确设置响应中的Content-Type标头。

相关问题