代码之家  ›  专栏  ›  技术社区  ›  user180574

为什么AJAX+会刷新页面?

  •  -2
  • user180574  · 技术社区  · 7 年前

    我尝试了很多方法来防止这种情况,但是没有什么能起到令人费解的作用。

    这是去get的路线。

    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对象
    • 将数据类型更改为文本
    • 将processData设置为false
    • 预防违约、停止传播、停止立即传播

    我很抱歉我不能上传开发代码,但你猜为什么刷新页面这么难?

    顺便说一下,对于POST来说,它工作得很好。

    这是相关的元素:

    <a href="/some" onClick="on_click(this); return false;"></a>
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   pretzelhammer Paras Bhattrai    7 年前

    而不是

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

    尝试

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

    快递文件: https://expressjs.com/en/api.html#res.json

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