提交请求时出现意外的 URL 更改

unexpected url changes when post request done

本文关键字:URL 更改 意外 请求 提交      更新时间:2023-09-26

我正在编写一个简单的Web服务,在Web UI(网址为"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" />

或使用返回关键字

  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;
}

只需将按钮设置为简单的按钮而不是提交按钮,键入="按钮"

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

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

因为当您将按钮设置为提交时,它会将您的页面提交到表单标签中编写的操作。