1

I am working on a service that randomly generates a URL and then uploads some pasted HTML code to the URL with PHP fwrite(). As a precation, I added a system to check if the URL has already been taken:

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 contains all the created URLs. When I first tried it, to test what would happen when the URL was a duplicate of a current URL, instead of using the random 7 letter string generator I just put one of the URLs already in the txt file.

This is the contents of existingurls.txt:

thehtmlworkshop.com/test1.html
thehtmlworkshop.com/test2.html
thehtmlworkshop.com/test3.html
thehtmlworkshop.com/test4.html
thehtmlworkshop.com/test5.html

Anyway, what should happen is that indexOf searches for all occurances of 'thehtmlworkshop.com/test4.html' and return it's position as 91 or whatever its position is and it would then tell the user that the randomly generated URL was taken. However, it seems to return -1 each time because it always goes to the submit form dialog.

NOTE: Yes, I am using jQuery.

4

2 回答 2

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).');
    }
});
于 2013-09-08T09:21:26.543 回答
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');
    }
  }
});
于 2013-09-08T09:23:23.597 回答