开发者

jQuery won't read JSON response (using $.post)

开发者 https://www.devze.com 2022-12-17 17:56 出处:网络
In a nutshell, I have a form, which upon submissions, sends data to a serverside script to process a function, return data in JSON format for me to parse 开发者_开发百科and spit back out onto the page

In a nutshell, I have a form, which upon submissions, sends data to a serverside script to process a function, return data in JSON format for me to parse 开发者_开发百科and spit back out onto the page.

  1. jQuery sends data to "createUser.php" via the $.post method

    $("#create_submit").click(function(){
        $.post("/createUser.php", {
            create_user_name: $('#create_user_name').val(),
            create_user_email: $('#create_user_email').val(),
            create_user_password: $('#create_user_password').val() },
            function(data){
                alert(data.response);
            }, "json");
    });
    
  2. "createUser.php" returns JSON data

    <?php
    header('Content-type: application/json');
    $return['response'] = 'hmm...';
    echo json_encode($return);
    exit;
    ?>
    

Maybe it's me, but I can't seem to get the alert that I need. What's going on!?


I think the data argument to your callback function already is the data, and has no response member.

Try function(data){ alert(data); }

Documentation: jquery.post


From what I can tell from your answers, JSON is only being outputted when you do the above POST request. If you do a normal GET request it works fine. To test this, change $.post to $.get (and clear the variables create_user_* if need be) and see if you get a response then.

If you do, then you need to check your createUser.php file and see why the POST request returns no JSON, but the GET request does. It looks like this is a PHP issue, not a JavaScript/JSON/jQuery issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消