gpt4 book ai didi

javascript - Ajax 函数仅在 "alert"时成功

转载 作者:行者123 更新时间:2023-11-29 10:32:57 25 4
gpt4 key购买 nike

编辑:我的问题不是 No response from MediaWiki API using jQuery 的副本.因为即使它是一个跨域请求,我也会正确触发 JSONP 行为,因为 jquery 会在后台自动发送一个回调参数。 (从我发布的链接可以看出 jQuery3100048749602337837095_1485851882249&_=1485851882253

EDIT2: 由@AnandMArora 解决。解决方案:

<input type="submit" onclick="getUserInput(event)" style="display:none"/>

和功能

getUserInput(evt) { evt.preventDefault();

但由于这是一条评论,我无法将其标记为答案。如果有此方法为何有效的解释(被阻止的默认行为是什么等),我将选择它作为答案。

我假设“警报”方法是为 AJAX 函数争取时间,因为它是异步的。但我不知道为什么我需要在这里争取时间。它应该只在 getUserInput() 使用 Input 参数调用 getWiki() 时执行。事实上,我查看了网络监视器,即使我们删除 alert("") 也会调用正确的 URL(假设提交了“batman”)。

请求网址:https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=batman&callback=jQuery3100048749602337837095_1485851882249&_=1485851882253

如果我手动打开这个链接,它工作正常。但是没有返回状态代码,控制台记录“错误!”

function getUserInput(){
var Input = document.getElementById("searchBox").value;
getWiki(Input);
alert(""); //If we remove this line the request fails
}

function generatePage(rawData) {
console.log(rawData);
var mainData = rawData.query.pages;
$.each(mainData, function(value){
console.log((mainData[value].title + " " + mainData[value].extract));
});

}


function getWiki(Input){
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=" + Input,
dataType: "JSONP",
type: "GET",
success: function (rawData) {
generatePage(rawData);
},
error: function() {
console.log("Error!")
}
});
}


$(document).ready(function(){


})

我用来提交的 html 是:

<form class="searchForm">
<input type="text" name="searchRequest" id="searchBox" >
<input type="submit" onclick="getUserInput()" style="display:none"/>
</input>
</form>

我的问题是:1)为什么会这样?2) 如何在不关闭 async 或在 ajax 函数上使用 setTimeout() 的情况下解决这个问题?

最佳答案

将 console.log 调用包装在一个函数中:

function getWiki(Input){
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=" + Input,
datatype: "JSONP",
type: "GET",
success:
function (rawData){
generatePage(rawData);
},
error:
function(){
console.log("Error!")
}
});
}

解释:

ajax 调用期望将函数定义传递给它的事件处理程序(在本例中为“成功”/“错误”)。

您为成功处理程序执行此操作。对于您的错误处理程序,您不是在推送一个函数定义,而是一个您实际上正在调用(console.log 方法)的函数。

将它包装在一个函数声明中(就像您为成功事件回调所做的那样)允许您定义什么回调何时被调用而不是被调用它是在线的。

关于javascript - Ajax 函数仅在 "alert"时成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41951824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com