簡體   English   中英

AJAX請求不起作用

[英]AJAX request doesn't work

我有一些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並單擊按鈕時,我沒有任何動作。 我認為,JS代碼是錯誤的,也可能是PHP。 請專家,誰可以幫助我並修改代碼?

編輯:這是問題所在。 你正在設置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>

這對我有用...嘗試這種方式直接把那個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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM