2014-10-03 106 views
-1

在一個html網頁中,我想要PHP響應顯示<span>..</span>。 任何人都可以告訴我該怎麼做,或者其他代碼有什麼問題? 感謝~~ ^^ 網頁代碼:如何通過使用ajax獲得php響應

<html> 
    <head> 
    <script type="text/javascript">  
     $("#submit").click(function(){ 
      $.ajax({ 
       type: 'get', 
       url: 'php/test.php', 
       dataType:'json', 
       success: function(data) { 
        //dosomething..... 
       }, 
      }); 
     }); 
    </script> 
    </head> 
    <body> 
     <form method="post"> 
      <input id="submit" type="button" value="next"> 
     </form> 
     <br><br><span id ="status"></span> 
    </body> 
</html> 

PHP代碼:

<?php 
echo ("success"); 
?> 
+0

請編輯您的問題與兩個文件,您要求的PHP頁面的文件和您將發送迴應的文件。 – Perry 2014-10-03 09:16:17

+0

您希望json可以打印文本。將dataType更改爲文本或在php中使用json_encode – Robert 2014-10-03 09:55:56

回答

0

後你得到的迴應做以下

$("#submit").click(function(){ 
      $.ajax({ 
       type: 'get', 
       url: 'php/test.php', 
       dataType:'json', 
       success: function(data) { 
        $("span#status").html(data); 
       }, 
      }); 
     }); 
0

這不會爲數據類型工作提供的將不會是JSON ... jQuery中的dataType屬性必須與使用PHP發送的數據類型相匹配。

爲了得到它用一個簡單的「成功」的消息時,您可以這樣做:

$("#submit").click(function(){ 
    $.ajax({ 
     type: 'get', 
     url: 'php/test.php', 
     dataType:'html', 
     success: function(data) { 
      $("span#status").html(data); 
     }, 
    }); 
}); 
0

因爲你使用dataType: "json",AJAX的功能,認爲它得到一個JSON陣列。但既然你只在你的php中用「succes」來回應,它不會被解析爲JSON。

你應該JSONify在PHP的輸出,json_encode(),之後你可以調用Ajax中的succes回調,或使用.done功能;

$("#submit").click(function(){ 
    $.ajax({ 
     type: 'get', 
     url: 'php/test.php', 
     dataType:'json', 
     success: function(data) { 
      $("span#status").html(data); 
     } 
    }); 
}); 

.done功能:

$("#submit").click(function(){ 
    $.ajax({ 
     type: 'get', 
     url: 'php/test.php', 
     dataType:'json', 
    }).done(function(data) { 
     $("span#status").html(data); 
    }); 
}); 

中,.done功能是在我看來,可讀性和可維護性更好。