2012-05-03 79 views
1

第一次尝试使用JSON。 这里是我的checklink.php:PHP-JSON:检查损坏的链接

function url_exists($url) { 
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_NOBODY, true); 
    curl_exec($ch); 
    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    // $retcode > 400 -> not found, $retcode = 200, found. 
    if ($retcode == 400){ 
    return "false"; 
    }else{ 
    return "true"; 
    } 
    curl_close($ch); 
} 
$response = array( 
    'location' => $location, 
    'status' => $status 
); 
$rr = url_exists($response['location']); 
echo json_encode($rr); 

JS部分:

function UrlExistsNew(url, callback) { 
    $.getJSON('checklink.php', { location: url }, function (data) { 
    callback.apply(null, data.status); 
}); 
} 
... 
UrlExistsNew($(this).val(), function(status){ 
     if(status === "false") $(element).css('background-color','#FC0'); 
     }); 
... 

看来PHP页面没有返回结果为JSON查询。

编辑:请注意,我忘了安装卷曲在我的服务器启用它。我希望没有人会错过这个。

+1

不必返回任何结果都只是真的还是假的? json在哪里? – thecodeparadox

+0

@thecodeparadox我不明白你想问什么。我不知道如何在PHP和JSON方面做什么。你的意思是json在哪里? – xperator

+0

尝试一些debbugging工具,如firebug或chrome开发工具.. – Vytautas

回答

1

OK,做试验后并试用8个小时。我终于得到了这个工作。非常感谢Vytautas。他教了我很多。主要是如何调试。

的人谁愿意来检查使用JSON + PHP +卷曲损坏的链接:

所有的
  1. 首先,检查你是否有卷曲安装在你的服务器中启用。
  2. 这些谁不明白卷曲:如果从您的网址回应,会有一个状态代码(如200或404)。如果输入的网址是空的,无效的或类似的东西,它会返回状态码0
  3. 如果你不能从PHP页面的正确响应,使用Firebug(控制台选项卡)来检查头部和响应。还可以使用断点来查看变量是否正确传递。

这里是PHP代码:

function url_exists($url) { 
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_NOBODY, true); 

    if(curl_exec($ch) === false) // These 2 line here are for debugging. 
     die('Curl error: ' . curl_error($ch)); 

    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch); 
    return $retcode; 
} 
$response = array(
    'status' => url_exists($_GET['location']) 
); 
echo json_encode($response) 

我做2件事错在PHP。我应该用$_GET['location']代替$location,另一个是$response而是采用了第二个变量。

而且js函数:

function UrlExistsNew(url, callback) { 
    $.getJSON('checklink.php', { location: url }, function (data) { 
    callback.call(null, data.status); 
}); 
} 

另一件事我做错了在JS是通过回调函数。我应该用callback.call代替callback.apply

简单的用法:

UrlExistsNew($(this).val(), function(status){ 
     if(status === 404) $(element).css('background-color','#FC0'); 
     }); 
1

你应该改变$rr = url_exists($response['location']);

$rr = array("status"=>url_exists($response['location']));

如您所愿

0
$rr = url_exists($response['location']); 
echo json_encode(array('status' => $rr)); 

得到JSON响应,并尝试这个办法:

UrlExistsNew($(this).val(), function(status){ 
    if(!status) $(element).css('background-color','#FC0'); 
}); 
+0

仍然无法正常工作。 – xperator

+0

尝试更新。还是行不通。我认为缺少一些东西。当我把断点放在$ .getJSON('checklink.php',{location:url},function(data){'它停止,但不在'callback.apply(null,data.status);'线 – xperator