简体   繁体   中英

how to set php array from the json ajax response

List of category shows.After clicking the category , we have listed products based on category,when i clicked category, get_category_products fucntion called, and return json output

[{"name":"watch","unit_price":"430.00"},{"name":"watch","unit_price":"250.00"}] 





function get_category_products(category){

        $.ajax({
            type: 'POST',
            url:    "get_category_products.php",
            async: true,
            data: 'category=' + category,
            cache: false,
                success: function(data)
                {               
                alert(data);                 
                }
            });

    }

Products List code

<div style="border:solid 1px red;width:230px;height:300px;overflow-y:scroll;">
        <h4>Items/Products</h4>
        <hr>
        <table border="0">  

         <tr>
             <?php $count =1; 
             $countItems = count($products_list);
             for($pr1=0;$pr1 < $countItems;$pr1++){  ?>                     
                   <td style="border:solid 1px black;width:100px;height:70px;text-align:center">
                    <table>
                        <tr><td colspan="2"><img src=""></td> </tr>
                        <tr>
                            <td><?php echo $products_list[$pr1]->name;?></td>
                            <td><?php echo $products_list[$pr1]->unit_price;?></td>
                        </tr>                    
                    </table>
                </td>
                    <?php if($count % 3 == 0) { ?> </tr><tr><?php } ?>
                <?php $count++; } ?>
         </table>

    </div>

How to decode json output and set to php array($products_list),how to display the products based on category using above code.

Add dataType: 'json' to the AJAX call, and jQuery will automatically decode it for you.

$.ajax({
    type: 'POST',
    url:    "get_category_products.php",
    async: true,
    data: { category: category},
    dataType: 'json', // *******
    cache: false,
    success: function(data) {               
        alert(data);                 
    }
});

I also recommend always passing an object as the data option, allowing jQuery to encode it for you (it will call encodeURLComponent , which encodes special characters correctly), rather than a param=value string.

You have to make refactoring your code, because you can't set to php json response from your server. Only java script can use json data and you can set your json to some JS object and update your template using only js. I recommend using underscore template , it's so easy.

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