Javascript indexOf()不起作用

时间:2013-09-08 09:16:01

标签: javascript jquery html indexof

我正在开发一个随机生成URL的服务,然后使用PHP fwrite().将一些粘贴的HTML代码上传到URL。作为预先准备,我添加了一个系统来检查URL是否已被采用:< / p>

var URL = "thehtmlworkshop.com/test4.html";
$('#existingurls').load('existingurls.txt');
var existing = $('#existingurls').html();
var isunique = existing.indexOf( URL );
if (isunique == -1) {
alert('Form submit');
} else {
alert('Whoops! Looks like the randomly generated URL was already taken. Please try again (this will be automatic in future).');
}

existingurls.txt包含所有已创建的网址。当我第一次尝试它时,为了测试当URL是当前URL的副本时会发生什么,而不是使用随机7字母字符串生成器,我只是将其中一个URL放在txt文件中。

这是existingurls.txt

的内容
thehtmlworkshop.com/test1.html
thehtmlworkshop.com/test2.html
thehtmlworkshop.com/test3.html
thehtmlworkshop.com/test4.html
thehtmlworkshop.com/test5.html

无论如何,应该发生的是indexOf搜索'thehtmlworkshop.com/test4.html'的所有出现并将其位置返回91或其位置是什么,然后它会告诉用户随机生成的URL已被删除。但是,它似乎每次都返回-1,因为它总是进入提交表单对话框。

注意:是的,我使用的是jQuery。

2 个答案:

答案 0 :(得分:2)

试试这个:

var URL = "thehtmlworkshop.com/test4.html";
$('#existingurls').load('existingurls.txt', function () {
    var existing = $('#existingurls').html();
    var isunique = existing.indexOf(URL);
    if (isunique == -1) {
        alert('Form submit');
    } else {
        alert('Whoops! Looks like the randomly generated URL was already taken. Please try again (this will be automatic in future).');
    }
});

答案 1 :(得分:2)

检查ajax函数Success调用的列表,确保它已加载。

var URL = "thehtmlworkshop.com/test4.html";
$('#existingurls').load('existingurls.txt', function(response, status, xhr) {
  if (status == "error") {
    var msg = "Sorry but there was an error: ";
    $("#error").html(msg + xhr.status + " " + xhr.statusText);
  } else {
    var isunique = existing.indexOf(URL);
    if (isunique == -1) {
      alert('Form submit');
    }
  }
});