javascript - post 请求完成后,url 发生意外更改

标签 javascript jquery html web

我正在编写一个简单的 Web 服务,在 Web UI 上(URL 为“localhost:9001”)有一个按钮可以触发函数 indexIt,该按钮会引发 POST 请求并且服务器响应与 json。

<button type="submit" id="indexButton" class="btn btn-primary" onclick="indexIt()">Index</button>

相关代码为:

function displayResponse(msg) {
    var shown = JSON.stringify(msg, null, 2);
    $(hintTextSelector).text(shown);
}

function indexDoneHint(response) {
    console.log(JSON.stringify(response));
    displayResponse(response);
}

function getLOptions() {
    return {
        "stem": $("#cb-index-stem").is(":checked"),
        "ignore": $("#cb-index-ignore").is(":checked"),
        "swDict": $("#lb-index-stopwords").val()
    }
}

function indexIt() {
    var indexOptions = getLOptions();
    var privateParam = {
        "method": "POST",
        "url": _getUrl("indexDoc"),
        "data": JSON.stringify(indexOptions)
    };
    $.extend(privateParam, commonParam);
    $.ajax(privateParam).done(indexDoneHint).error(onError);
}

问题是,当我按下按钮触发请求时,URL 将更改为“localhost:9001/?” (尾随 /?)已添加。

奇怪的是,当我使用开发人员控制台并调用 indexIt() 时,页面仍然是“localhost:9001”

最佳答案

如果您使用按钮<button>在您的表单中,然后单击它会自动提交表单。 使用输入标签代替按钮标签,即 <input type="button" id="indexButton" class="btn btn-primary" onclick="indexIt()" value="Index It" />

或使用 return 关键字

  1. <button type="submit" id="indexButton" class="btn btn-primary" onclick="return indexIt()" >Index</button>

  2. 在你的 javascript 函数“indexIt()”最后使用“return false”,这样它将运行你的 js 代码并停止执行。

    function indexIt() {
    var indexOptions = getLOptions();
    var privateParam = {
        "method": "POST",
        "url": _getUrl("indexDoc"),
        "data": JSON.stringify(indexOptions)
    };
    $.extend(privateParam, commonParam);
    $.ajax(privateParam).done(indexDoneHint).error(onError);
    
   return false;
}

关于javascript - post 请求完成后,url 发生意外更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35980507/

相关文章:

javascript - 加载 gif 不是动画?

javascript dom 注入(inject)元素不会在 IE 中拾取 css 样式

javascript - JS验证IP :Port

javascript - 单击创建时,引导标签之间的空格会被删除

javascript - 如何通过javascript获取列中<a>的值

javascript - mailListner - 无法读取未定义的属性 'on'

javascript - 如何在不将用户重定向到该 URL 页面的情况下发送 GET 值?

javascript - 使用 jquery ajax 在 window.location 重定向后在下一页的 div 中写入 html 文本

html - css,固定元素不会导致 body 滚动(被切断)

javascript - 使用 Angular 对表格行上的按钮进行动画处理,导致整行的按钮进行动画处理