我试图制作隐藏的div,显示何时找到.txt文件。 我希望div显示.txt文件的内容。
这可能吗?
我尝试使用jQuery但没有成功。
想法很简单:具有常量维度的div框显示.txt文件的内容,该文件位于服务器上的同一文件夹中,但是当没有任何.txt文件时,div变为隐藏(例如在jQuery $("p").hide();
中)。
答案 0 :(得分:3)
据我所知,这是不可能的。您可以对php页面执行ajax调用,该页面将检查服务器上是否存在该文件并返回一些内容,但使用jQuery直接加载/检查是违反浏览器安全性的,因此他们不应该允许您这样做。
答案 1 :(得分:1)
这取决于用法,但是说你有文本的div,你可以通过在css中将它设置为display:none来使其不可见。 现在,您可以尝试使用ajax调用获取文件,也可以使用ajax头调用来检查服务器上是否存在该文件。 如果文件存在,只是让文件更快,因为头部调用仅检查它是否存在,并且需要另一个ajax调用来获取文件的内容,但是头部调用更快它不存在,因为它'获取文件的内容。
编辑:但由于该文件不存在,因此无需获取,因此这里可能不需要头部调用,因为“get”在两种情况下都会更快,但该示例仍然显示如何检查是否文件存在于服务器上,如果它存在或不存在则执行某些操作。
看起来像这样。
$.ajax({
url:'http://www.mysite.com/myfile.txt',
type:'HEAD',
error: function()
{
//file does not exists, no need to do anything
},
success: function()
{
//file exists get the file and put in the textcontainer and make that visible
$.ajax({
url:'http://www.mysite.com/myfile.txt',
success: function(data)
{
$("#textcontainer").show().text(data);
}
}
});
或者另一种方式是使用display:block etc显示textcontainer:
$.ajax({
url:'http://www.mysite.com/myfile.txt',
type:'GET',
error: function()
{
//file does not exists, hide the textcontainer
$("#textcontainer").hide();
},
success: function(data)
{
//file exists get the file and put in the textcontainer that is already visible
$("#textcontainer").text(data);
}
});
答案 2 :(得分:0)
根据http://api.jquery.com/jQuery.get/,您可以处理错误:
如果带有jQuery.get()的请求返回错误代码,它将无声地失败,除非该脚本还调用了全局.ajaxError()方法。
另请参阅http://api.jquery.com/jQuery.ajax/#jqXHR
该页面的一个例子:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });