Jquery$.get()使用JSON从php脚本返回未定义的结果


Jquery $.get() returns undefined result from php script with JSON

更新

呃,我试着看更多的教程,我决定先使用$.get((,因为它更容易,也有利于起点。。

所以这是脚本,我认为它工作正常,除了它给出了未定义的结果

<!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"按钮时,它显示未定义的

这是因为您的选择器是错误的

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

应该是

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

或者给你的按钮一个id,并使用带有# 的id选择器

 <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>');
});

您需要选择正确的按钮来绑定点击事件。

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

我不能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

您可以使用许多不同的选择器将单击事件附加到该按钮。

编辑:也将输入类型更改为按钮。。。submit用于表单