How to get jSON response into variable from a jquery script

前端 未结 4 1918
小鲜肉
小鲜肉 2020-12-13 15:00

I am having trouble with my jquery script below, this is a basic stripped down version and even it will not work, I have the php file that the jquery script makes a call to

相关标签:
4条回答
  • 2020-12-13 15:12

    Here's the script, rewritten to use the suggestions above and a change to your no-cache method.

    <?php
    // Simpler way of making sure all no-cache headers get sent
    // and understood by all browsers, including IE.
    session_cache_limiter('nocache');
    header('Expires: ' . gmdate('r', 0));
    
    header('Content-type: application/json');
    
    // set to return response=error
    $arr = array ('response'=>'error','comment'=>'test comment here');
    echo json_encode($arr);
    ?>
    
    //the script above returns this:
    {"response":"error","comment":"test comment here"}
    
    <script type="text/javascript">
    $.ajax({
        type: "POST",
        url: "process.php",
        data: dataString,
        dataType: "json",
        success: function (data) {
            if (data.response == 'captcha') {
                alert('captcha');
            } else if (data.response == 'success') {
                alert('success');
            } else {
                alert('sorry there was an error');
            }
        }
    
    }); // Semi-colons after all declarations, IE is picky on these things.
    </script>
    

    The main issue here was that you had a typo in the JSON you were returning ("resonse" instead of "response". This meant that you were looking for the wrong property in the JavaScript code. One way of catching these problems in the future is to console.log the value of data and make sure the property you are looking for is there.

    Learning how to use the Chrome debugger tools (or similar tools in Firefox/Safari/Opera/etc.) will also be invaluable.

    0 讨论(0)
  • 2020-12-13 15:13

    You should use data.response in your JS instead of json.response.

    0 讨论(0)
  • 2020-12-13 15:20

    Look out for this pitfal: http://www.vertstudios.com/blog/avoiding-ajax-newline-pitfall/

    Searched several houres before I found there were some linebreaks in the included files.

    0 讨论(0)
  • 2020-12-13 15:37

    Your PHP array is defined as:

    $arr = array ('resonse'=>'error','comment'=>'test comment here');
    

    Notice the mispelling "resonse". Also, as RaYell has mentioned, you have to use data instead of json in your success function because its parameter is currently data.

    Try editing your PHP file to change the spelling form resonse to response. It should work then.

    0 讨论(0)
提交回复
热议问题