2015-11-29 33 views
-1

我對這個php比較新,我試圖從我的javascript文件訪問/執行一個php文件,並讓它出現在我的html中。有人告訴我,$的getJSON是做到這一點的最好的方式,但我看不到我的PHP腳本過去被逼到我的html:我的jquery沒有訪問php文件

HTML:

<!doctype html> 
<html lang="en"> 

<head> 
    <div class="button"></div> 
    <script src="http://code.jquery.com/jquery-1.7.js"></script> 
    <script src="Test.js" type="text/javascript"></script> 
</head> 
<body> 
    <a href="#" id="getdata-button">Get JSON Data</a> 
    <div id="showdata"></div> 
</body> 

</html> 

的Javascript:

$(document).ready(function(){ 
    $(document).on("click","#getdata-button", function() { 
    //test Confirmed 
    alert('hello8'); 
     $.getJSON('Test.php', function(data) { 
      //noresponse 
      alert('hello5'); 
      $('#showdata').html("item1="+data.item1+" item2="+data.item2+" item3="+data.item3+""); 
     }); 
    }); 
}); 

測試。 php:

< ?php 
$items = array( 
    'item1' => 'I love jquery4u', 
    'item2' => 'You love jQuery4u', 
    'item3' => 'We love jQuery4u' 
); 

header('Content-type: application/json'); 
echo json_encode($items); 

?> 

我的預期結果是html中的item1/item2/item3。

+0

無論如何,它在控制檯中說了什麼? –

+0

檢查我的答案,試試看,並告訴我它是否正常工作。 –

回答

0

php之前有一個(space)字符:

< ?php 

將其更改爲:<?php

不是,刪除此:

header('Content-type: application/json'); 

,或是更換:

header('Content-type: text/javascript'); 

我不知道爲什麼,但它的作品。

+0

我做了這些改變,但沒有發生任何不同,我期待通過項目1到3回到網頁。 – bawg2005

+0

PHP和可見文件都在同一個文件夾中嗎? –

+0

控制檯@ bawg2005中顯示了什麼? –