我正在编写一个简单的 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 关键字
<button type="submit" id="indexButton" class="btn btn-primary" onclick="return indexIt()" >Index</button>
在你的 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/