如果网站存在AJAX,则验证

时间:2012-09-21 03:58:21

标签: php jquery

我正在尝试检查一个网站是否存在ajax调用,但我不确定我是否正确。在我的页面上,我点击了

上的URL
$("#go").click(function() {
    var url = $("#url").val();
    $.ajax({
        type: "POST",
        url: "/ajax.php",
        data: "url="+url,
        success: function(){
          $("#start").remove();
        },      
        error: function(){
        alert("Bad URL");
        }
    });     
});

a =然后检查ajax.php

$url = $_POST['url'];

ini_set("default_socket_timeout","05");
set_time_limit(5);
$f=fopen($url,"r");
$r=fread($f,1000);
fclose($f);
if(strlen($r)>1) {
    return true;
} else {
    return false;
}

无论如何我似乎都成功了......我缺少什么?

3 个答案:

答案 0 :(得分:1)

正如Nemoden所说,即使返回false,也会收到成功消息。 您需要检查返回的数据,然后删除元素。

例如

$("#go").click(function() {
    var url = $("#url").val();
    $.ajax({
        type: "POST",
        url: "/ajax.php",
        data: "url="+url,
        success: function(response){
          if (response == 'whatever you are returning') {
              $("#start").remove();
          }
        },      
        error: function(){
        alert("Bad URL");
        }
    });     
});

答案 1 :(得分:1)

  

无论如何我似乎都成功了......我缺少什么?

这非常简单明了。

由于这个原因:

// You have no idea what server respond is.
// that is you can't parse that respond
success: function(){
   $("#start").remove();
}

哪个应该是

success: function(respond){

   //you don't have to return TRUE in your php
   //you have to echo this one instead
   if ( respond == '1'){
     $("#start").remove();
   } else {
     //handle non-true if you need so
   }
}

在php中替换它:

if(strlen($r)>1) {
    return true;
} else {
    return false;
}

if(strlen($r)>1) {
    print true; //by the way, TRUE is a constant and it equals to == 1 (not ===)
}

哦,是的,也不要忘记解决这个问题:

data: "url="+url

data : {"url" : url}

答案 2 :(得分:0)

只要服务器端脚本返回答案(没有连接错误或服务器端错误),就会调用成功回调。这是回答你的问题吗?

看到区别:

$("#go").click(function() {
    var url = $("#url").val(),
        ajax_data = {url: url};
    $.post({
        "/ajax.php?cb=?",
        ajax_data,
        function(response){
          if (response.status) {
            // URL exists
          }
          else {
            // URL not exists
          }
          $("#start").remove();
        },      
        'json'
    });     
});

php后端:

printf('%s(%s)', $_GET['cb'], json_encode(array('status' => (bool)$url_exists)));