PHP-JSON:检查损坏的链接

第一次尝试使用JSON。 这是我的checklink.php:

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查询。

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

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

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

按预期获得json响应

好的,经过8小时的测试和试验。 我终于得到了这个工作。 非常感谢Vytautas 。 他教了我很多东西。 主要是如何调试。

对于想要使用JSON + PHP + CURL检查损坏链接的任何人:

  1. 首先,检查服务器中是否安装了curl并启用了curl
  2. 那些不理解curl的人:如果您的url有回复,则会有状态代码(如200或404)。 如果输入的URL为空白,无效或类似,则返回状态码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) 

我在php中做了两件事。 我应该使用$_GET['location']而不是$location而另一个是$response而不是使用第二个变量。

和jsfunction:

 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'); }); 
 $rr = url_exists($response['location']); echo json_encode( array('status' => $rr) ); 

试试这个:

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