如何在Javascript中获取给定URL的内容类型? [英] How to get content type of a given url inside Javascript?
问题描述
我想知道用户在我的Javascript代码中输入的给定网址的内容类型。实际上,我有一个下拉列表(html,csv,xls等),我想在用户输入url时这样做,我想检测url内容的类型并根据这个类型我想要设置我的下拉列表的值(html,csv,xls等)。我知道,我可以像这样使用Ruby获取内容类型:
I want to know the content type of a given url input by the user inside my Javascript code. Actually, I have a drop-down list (html,csv,xls etc.) and I want to make it so when the user inputs an url, I want to detect the type of the content of the url and based on this type I want to set the value of my drop-down list (html,csv,xls etc.). I know, I can get the content type using Ruby like this :
require 'open-uri'
str = open('http://example.com')
str.content_type #=> "text/html"
或者,我也可以使用curl获取内容然后解析它了解内容类型。但是,我需要在我的Javascript代码中执行此操作,因为我需要在上面解释。有什么想法吗?
or, also, I could use curl to get the content and then parse it to know the content type. But, I need to do this inside my Javascript code because of my need explained above. Any thought ?
EDIT_1:
我在javascript中尝试了这段代码:
I tried this code in my javascript :
$("#wiki_form_url").change(function(){
$.ajax({
type: "GET",
url: "content.rb",
data: {
// input_url: $("#wiki_form_url").val()
},
dataType: "html"
}).done(function (data) {
// `data` contains the content-type
alert('Success !!!');
}).fail(function () {
alert("failed AJAX call");
});
});
我有一个ruby脚本content.rb我在其中:
I have a ruby script content.rb inside which I do :
require 'open-uri'
str = open('http://www.ofdp.org/benchmark_indices/25')
str.content_type
但是,它似乎不起作用。我得到了Ajax失败。可能是因为脚本content.rb的url路径?我该如何在这里指定脚本路径? (相对或绝对)
But, it does not seem to work. I am getting Ajax failure. May be it's because of url path of the script content.rb ? How should I specify a script path here ? (Relative or absolute)
推荐答案
Atlast我可以在@Ian的帮助下找出整件事。这是我完成的代码:在javascript文件中:
Atlast I could figure out the whole thing with the great help of @Ian. Here is my completed code : In javascript file :
$("#wiki_form_url").change(function () {
$.ajax({
type: "GET",
url: "/wiki_forms/content",
data: {
input_url: $("#wiki_form_url").val()
},
dataType: "text"
}).done(function (data) {
// `data` contains the content-type
alert('Success');
console.log(data);
// alert(data);
}).fail(function () {
alert("failed AJAX call");
});
});
在我的wiki_forms控制器中,我创建了一个名为content的新方法:
Inside my wiki_forms controller I created a new method named content :
def content
req = open(params[:input_url])
render :text => req.content_type
end
然后在routes.rb文件中添加了一条新路由:
Then added a new route in routes.rb file :
get "/wiki_forms/content" => 'wiki_forms#content'
并使用 / wiki_forms / content 作为ajax请求网址。而且,现在一切都很顺利。
and used /wiki_forms/content as the ajax request url. And, everything is working nicely now.
这篇关于如何在Javascript中获取给定URL的内容类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!