在jQuery的AJAX响应中获取请求数据

时间:2017-12-10 01:25:23

标签: javascript jquery ajax

我们说我做了一个词典应用程序,在那里我检查是否存在某个单词。我有一个文本输入和一个按钮:

<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的信息和数据?

2 个答案:

答案 0 :(得分:2)

您可以使用您想要的任何内容修改beforeSend中的jQuery xhr对象,然后成功访问它,或者然后()或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>

答案 1 :(得分:0)

以下是我要做的事情:

$("#button").click(function () {
    var word = $("#word").val();
    $.ajax({
        url: "check.php?word=" + word,
        method: 'GET',
        success: function (data) {
            alert(word);
        }
    });
});

编辑:从Robo Robok的评论中删除,他是正确的。

相关问题