javascript 在 jQuery 中从 AJAX 调用外部 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18470738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call external URL from AJAX in jQuery
提问by Reynier
I need to call a external URL (not in my development server) that returns JSON response. Doing some research I found thisand thispost and tried almost every, right now my code is this:
我需要调用一个返回 JSON 响应的外部 URL(不在我的开发服务器中)。做了一些研究,我发现了这个和这个帖子,几乎每一个都尝试过,现在我的代码是这样的:
$("#query").on("keyup", function(e) {
if (e.which !== 32) {
var value = $(this).val();
var noWhitespaceValue = value.replace(/\s+/g, '');
var noWhitespaceCount = noWhitespaceValue.length;
if (noWhitespaceCount % 3 === 0) {
var request = $.ajax({
type: 'GET',
data: "text=" + $(this).val(),
url: "http://192.168.0.159:3000/products/search/all",
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
request.abort();
}
});
}
}
});
But it's not working, so what is the best way to achieve this?
但它不起作用,那么实现这一目标的最佳方法是什么?
回答by josecatalani
How many times you bind the "keyup" ? Have you tried abort an previous request?
您绑定“keyup”多少次?您是否尝试过中止先前的请求?
$("#query").on("keyup", function(e) {
if (e.which !== 32) {
var value = $(this).val();
var noWhitespaceValue = value.replace(/\s+/g, '');
var noWhitespaceCount = noWhitespaceValue.length;
if (noWhitespaceCount % 3 === 0) {
/* Aborting previous Requests */
if(request) request.abort();
var request = $.ajax({
type: 'GET',
data: "text=" + $(this).val(),
url: "http://192.168.0.159:3000/products/search/all",
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
request.abort();
}
});
}
}
});