简体   繁体   中英

AJAX request returning JSON, not working

I'm probably misunderstanding JSON, but why this code doesn't work?

HTML

<html>
    <head>
        <title>Test</title>
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/main.js"></script>
    </head>
    <body>
        <div class="response">
            Name: <span class="name"></span><br>
            Password: <span class="password"></span><br>
    </body>
</html>

MAIN.JS

$(document).ready(function(){

    $.ajax({
        type: "POST",
        url: 'action.php',
        dataType: 'json',
        success: function(msg){
            $.each(msg, function(index, value){
                if (index == 'name') { $('.name').html(value.name); }
                if (index == 'password') { $('.password').html(value.password); }
            });
        },

        error: function(){
            $('.response').html("An error occurred");
        }
    });

});

ACTION.PHP

<?php

$array = array(
    0 => array(
        'name' => "Charlie",
        'password' => "none"
    ),
    1 => array(
        'name' => "Tree",
        'password' => "tree"
    )
);

echo json_encode($array);

?>

In your javascript, index will be '0' and '1', never 'name' and 'value':

    success: function(msg){
        $.each(msg, function(index, value){
            $('.name').html(value.name);
            $('.password').html(value.password);
        });
    },

Of course, as this stands now, you'll be setting your fields twice, and only the last one will "stick"

If you wanted use just the 'Charlie' result, then

    success: function(msg){
        $('.name').html(msg[0].name);
        $('.password').html(msg[0].password);
    },

and for 'Tree', just change the array subscripts to 1

It should be

if (index == 'name') { $('.name').html(value); }
if (index == 'password') { $('.password').html(value); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM