4

我有一些 PHP 脚本、HTML 表单和 JS 代码(AJAX):

if(isset($_POST['site'])){

$homepage = file_get_contents("http://".$_POST['site']);
preg_match('%<meta.*name="keywords".*content="(.*)"\s+/>%U', $homepage, $regs);

if(count($regs))
{
$myString = implode('', $regs );  
 print_r($myString);
}
}


?>


<form id=payment method="post" name="forma1">
<label for=name>ENTER www.bbc.com:</label>
<input id="name" type=text placeholder="Write here..."         name="site">
<input type="submit" value="START" name="searchbutton" id="sb">
</form>

<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function(){
         $('#payment').submit(function(e){
            e.preventDefault();
           $.ajax({
                 type: "POST",
                url: $(this).attr('action'),
                data: $(this).serialize(),
                dataType: 'json',
                success: function(data)
                {
                    alert("OK, AJAX IS WORKING");
                }
            });
        });
    });
    </script>

没有 JS 代码一切正常。PHP 脚本也可以正常工作,当我单击按钮时,在收到所需信息后。但是当我尝试使用 AJAX 并单击按钮时,我没有任何操作。我认为,thant JS 代码是错误的,也可能是 PHP。请问各位高手,谁能帮我修改一下代码?

4

2 回答 2

0

这对我有用...尝试这种方式直接将 url 放在那里,就像我做的那样和错误响应,这样如果它不起作用,它会告诉你什么样的错误并删除 dataType:'json'

<?php  if(isset($_POST['site'])){

 var_dump($_POST); 
 exit;


}
?>
<html>

<head>
 <script src="http://code.jquery.com/jquery-latest.js"></script>    
<script type="text/javascript">
    $(document).ready(function(){
         $('#payment').submit(function(e){
            e.preventDefault();
           $.ajax({
                 type: "POST",
                url: 'test.php',
                data: $(this).serialize(),
                success: function(data)
                {
                    alert("OK, AJAX IS WORKING"+data);
                },
                 error:   function(xhr, ajaxOptions, thrownError) { alert(xhr.status);
                                         } 
            });
        });
    });
    </script>
</script>

</head>     

<div>
<form id="payment"    method="post" name="forma1">
        <label for=name>ENTER www.bbc.com:</label>
        <input id="name" type=text placeholder="Write here..."         name="site">
        <input type="submit" value="START" name="searchbutton" id="sb">
</form>

</div>  


</html> 
于 2012-08-30T04:11:13.060 回答
0

编辑:这是问题所在。您正在设置dataType: json,但您的 PHP 没有返回 JSON。删除dataType: 'json'线。也不要忘记开始 PHP 标记:<?php.
编辑 2:好的,这是获取元标记并显示它们的代码。PHP:

$homepage = file_get_contents("http://".$_POST['site']);
preg_match('%<meta.*name="keywords".*content="(.*)"\s+/>%U', $homepage, $regs);
if(count($regs)) {
  $myString = implode('', $regs );  
 echo $myString;
}

(上面的代码是你的问题 - 我假设它有效)Javascript AJAX成功函数:

success: function (data) {
  $('#metaTags').text(data)
}

HTML:

<div id="metaTags"></div>
于 2012-08-30T01:01:57.277 回答