jQuery $.post processing JSON response

后端 未结 3 2031
眼角桃花
眼角桃花 2020-12-06 10:21

I\'m having trouble figuring out how to properly read my JSON response from a jQuery $.post() request.

In the below jQuery code, I populate an associative array of s

相关标签:
3条回答
  • 2020-12-06 10:26

    Ok then..the data object you're getting back from the post is: {"id":"abc","images":[{"color123":"somelink.com\/123","color223":"somelink.com\/‌​223"}]};

    If you change your alert, you'll find the values you're looking for:

    $.post(
        "test.php",
        { id: product_id, "images[]": jQuery.makeArray(image_links) },
        function(data) {
            var response = jQuery.parseJSON(data);
    
            var images = response.images[0];
            for (var i in images){
                alert(images[i]);
            }
        }
    );
    
    0 讨论(0)
  • 2020-12-06 10:32

    $.post expects xml by default, you need to specify the response format

    $.post(
        "test.php",
        { id: product_id, images : jQuery.makeArray(image_links) },
        function(response) {
            // Response is automatically a json object
            for(var i = 0; i < response.images.length; i++) {
                alert(response.images[i]);
            }
        }, 'json' // <-- HERE
    );
    

    Also, consider adding a content type header in your php script

        <?php
        header("Content-type: application/json"); // Adding a content type helps as well
        $product_id = $_POST['id'];
        $images = $_POST['images'];
    
        $response = array();
        $response['id'] = $product_id;
        $response['images'] = $images;
    
        echo json_encode($response);
        ?>
    
    0 讨论(0)
  • 2020-12-06 10:35

    A pretty basic example would be something like :

    $.post('test.php', {"id": 42}, function (json) {
     console.log(json);
    }, 'json');
    

    PHP example

    $number = rand(1,$_POST["id"]);
    return print json_encode($number);
    
    0 讨论(0)
提交回复
热议问题