假设我制作了一个词典应用程序,我在其中检查某个单词是否存在。我有一个文本输入和一个按钮:
<input type="text" id="word">
<input type="button" id="button">
我希望服务器响应 1
(有效词)或 0
(无效词)。
在我的 jQuery 脚本中,我发送了一个 AJAX 请求:
$("#button").click(function () {
$.ajax({
url: "check.php?word=" + $("#word").val(),
method: 'GET',
success: function (isValid, textStatus, xhr) {
// Can I read the URL from the xhr to know which word was the request for?
}
});
});
问题是,当响应返回时,我不再知道它是针对哪个词的。我知道我可以将单词附加到服务器的响应中,但我很好奇是否可以通过其他方式完成。
我很确定我可以将这条信息附加到原始 XHR,然后在成功回调中读取它,但我的问题是:成功回调中的 XHR 是否包含有关请求的 URL 和数据的信息?
最佳答案
您可以在 beforeSend 中修改 jQuery xhr 对象,然后在成功或 then() 或 done() 回调中访问它
$.ajax({
url: 'http://httpbin.org/get',
data:{foo:'bar'},
beforeSend:function(jQxhr){
jQxhr.something='another thing';
},
success:function(res,statusText,jQxhr){
console.log('"Something" in success() ', jQxhr.something)
}
}).then(function(res,statusText,jQxhr){
console.log('"Something" in then() ', jQxhr.something)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 在 jQuery 的 AJAX 响应中获取请求数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47734992/