2013-05-17 24 views
1

更新

錯誤我試試,看更多的教程,我決定使用$。獲得()首先因爲它更容易和良好的出發點..

所以這是劇本,我認爲它工作正常,除了它給未定義的結果

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Display Json</title> 
<script src="../_js/jquery-1.7.2.min.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function() 
    { 
     $('#jsonButton').click(function() 
     { 
      var data = '' 
      $.get('getJson.php', data, response); 
     });//end click 
    });//end ready 

    function response(data) 
    { 
     $('#display').prepend('<p>' + data.name + data.phone + '</p>'); 
    } 
</script> 
<body> 
    <div id="display"> 

      <input type="button" id="jsonButton" value="getJson!" /> 

    </div> 
</body> 
</html> 

,這是getJson.php簡單的PHP腳本,返回簡單的JSON對象:

$data['name'] = 'username'; 
$data['phone'] = '08989808089'; 

header('Content-Type: application/json'); 
echo json_encode($data); 

當我點擊 '的getJSON' 按鈕,將顯示未定義

+0

你使用瀏覽器的調試器類似Firebug或Chrome開發工具? – palmplam

回答

3

,這是因爲你的選擇是不正確

$('submit').click(function() 
//-^^^^^----here 

應該

$('input[name="submitButton"]').click(function(){ 
    .... 
} 

或給一個id到您的按鈕並使用ID seletor #

<input type="submit" name="submitButton" value="getJson!" id="getjson"/> 

    $('#getjson').click(function(){ 
    ...... 

或者您也可以使用

$('input:submit').click(function(){ 
    ..... 
}); 

更新

和不確定的,你可以調用回調函數.....

$.get('getJson.php', data, function(data){ 
    $('#display').prepend('<p>' + data.name + data.phone + '</p>'); 
}); 
+0

updated..check未定義電話的答案 – bipen

+1

與我自己的答案差不多相同的答案......同時發佈......還有3個upticks和一個可接受的答案。並且幾乎沒有來自操作的反饋。不會再爲他的問題煩惱。 –

0

您需要選擇正確的按鈕綁定點擊事件。

$('input:submit').click(function(){ }); 
0

我不是100%肯定你有選擇的權利。我會給按鈕一個id並使用它。

<script type="text/javascript"> 
    $(document).ready(function() 
    { 
     $('#mybutton').click(function() 
     { 
      $.ajax(
      { 
       type: 'GET', 
       url: 'getJson.php', 
       dataType: 'json', 
       success: function(jsonData) 
       { 
        $('#display').prepend('<p>' + jsonData.name + ' ' + jsonData.phone + '</p>'); 
       } 
      });//end ajax 
      return false; 
     });//end click 
    });//end ready 

</script> 
    <body> 
     <div id="display"> 

       <input id="mybutton" type="button" name="submitButton" value="getJson!" /> 

     </div> 
    </body> 

閱讀有關正確的jQuery選擇這裏

http://www.w3schools.com/jquery/jquery_ref_selectors.asp

有,你可以使用點擊事件附加到按鈕許多不同的選擇。

編輯:修改輸入的類型按鈕,以及...提交是一種形式

+0

ermm thx爲指出,改變後,它仍然沒有工作:( – mohur

+0

其實你應該改變輸入類型的按鈕以及 –

相關問題