在 Jquery/Javascript 中检查 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4301968/
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
Checking a Url in Jquery/Javascript
提问by user474632
All I need is a method that returns true if the Url is responding. Unfortunately, I'm new to jQuery and it's making my attempts at writing that method rather frustrating.
我只需要一个方法,如果 Url 响应,则返回 true。不幸的是,我是 jQuery 的新手,它使我尝试编写该方法相当令人沮丧。
I've seen several examples of jQuery using .ajax, but the code is consistently failing on me. What's wrong?
我已经看到了几个使用 .ajax 的 jQuery 示例,但是代码一直在我身上失败。怎么了?
var urlExists = function(url){
//When I call the function, code is still executing here.
$.ajax({
type: 'HEAD',
url: url,
success: function() {
return true;
},
error: function() {
return false;
}
});
//But not here...
}
回答by Han Seoul-Oh
That isn't how AJAX works. AJAX is fundamentally asynchronous (that's actually what the first 'A' stands for), which means rather than you call a function and it returns a value, you call a function and pass in a callback, and that callback will be called with the value.
这不是 AJAX 的工作方式。AJAX 从根本上是异步的(这实际上是第一个 'A' 代表的意思),这意味着不是调用函数并返回值,而是调用函数并传入回调,然后将使用值调用该回调.
(See http://en.wikipedia.org/wiki/Continuation_passing_style.)
(参见http://en.wikipedia.org/wiki/Continuation_passing_style。)
What do you want to do after you know whether the URL is responding or not? If you intended to use this method like this:
知道 URL 是否响应后,您想做什么?如果您打算像这样使用此方法:
//do stuff
var exists = urlExists(url);
//do more stuff based on the boolean value of exists
Then what you have to do is:
那么你需要做的是:
//do stuff
urlExists(url, function(exists){
//do more stuff based on the boolean value of exists
});
where urlExists()
is:
在哪里urlExists()
:
function urlExists(url, callback){
$.ajax({
type: 'HEAD',
url: url,
success: function(){
callback(true);
},
error: function() {
callback(false);
}
});
}
回答by alex
urlExists()
can not return because it needs wait for the request.
urlExists()
不能返回,因为它需要等待请求。
Either pass it a callback, or make it synchronous (not recommended, because it locks the browser).
要么传递回调,要么使其同步(不推荐,因为它会锁定浏览器)。
var urlExists = function(url, callback) {
if ( ! $.isFunction(callback)) {
throw Error('Not a valid callback');
}
$.ajax({
type: 'HEAD',
url: url,
success: $.proxy(callback, this, true),
error: $.proxy(callback, this, false)
});
};
Then you can do
然后你可以做
urlExists('/something', function(success) {
if (success) {
alert('Yay!');
} else {
alert('Oh no!');
}
});
It also worth mentioning the same origin policy.
还有值得一提的同源政策。
Also, returning from an anonymous function's scope will not returnin the parent function (like in your original example). It just returns that inner function. To return from an inner to a parent, set a flag and return it.
此外,从匿名函数的范围返回不会在父函数中返回(就像在您的原始示例中一样)。它只是返回那个内部函数。要从内部返回到父级,请设置一个标志并将其返回。
回答by Simon
Basically, there is nothing wrong with your code. See it work here: http://jsfiddle.net/PK76X/
基本上,您的代码没有任何问题。在这里看到它的工作:http: //jsfiddle.net/PK76X/
My guess is that you're using it to check the availability of content on a different domain, which fails because browsers don't allow cross domain ajax-requests.
我的猜测是您正在使用它来检查不同域上内容的可用性,这会失败,因为浏览器不允许跨域 ajax 请求。
回答by slebetman
If the url is from the same domain as your page you can do it. But if it is from a different domain, for example google.com, then it will fail due to cross domain security.
如果 url 与您的页面来自同一个域,您可以这样做。但是如果它来自不同的域,例如 google.com,那么由于跨域安全性,它将失败。
回答by Dan
In general, you should probably run your script in Firefox using the firebug plugin. It will give you the details needed to solve the issue.
通常,您应该使用 firebug 插件在 Firefox 中运行您的脚本。它将为您提供解决问题所需的详细信息。
The ajax and post methods are asynchronous, so you should handle the result in a callback method.
ajax 和 post 方法是异步的,因此您应该在回调方法中处理结果。
回答by Ohad
AJAX is basically asynchronous, and that's why the behavior you are describing. I've used the following, which is free of cross origin, to get a simple true/false indication whether a URL is valid, in a synchronous manner:
AJAX 基本上是异步的,这就是您所描述的行为的原因。我使用了以下内容,它没有交叉源,以同步方式获得一个简单的真/假指示 URL 是否有效:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
The usage is then trivial:
用法很简单:
var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Hope this helps
希望这可以帮助