简体   繁体   中英

PHP: Retrieving JSON via jQuery ajax help

Hey I have a script that is creating and echoing a JSON encoded array of magento products.

I have a script that calls this script using jQuery's ajax function but I'm not getting a proper response. When the GET request is performed firebug displays

GET http://localhost.com/magento/modules/products/get.php 200 OK then a **red cross** then 361ms 

This is the script that creates the array:

 // Load product collection
 $collection = Mage::getModel('catalog/product')->getCollection();
 $collection->addAttributeToSelect('name');
 $collection->addAttributeToSelect('price');

 $products = array();

 foreach ($collection as $product){
     $products[] = array("price" => $product->getPrice(),
                         "name" => $product->getName() );
 }

 header('Content-Type: application/x-json; charset=utf-8');
 echo(json_encode($products));

Here is my jQuery:

<script type="text/javascript">
        $(document).ready(function() {
            $.ajax({
                type: "GET",
                url: "http://localhost.com/magento/modules/products/get.php",
                    success: function(products)
                    {
                        $.each(products,function()
                        {
                            var opt = $('<option />');
                            opt.val(this.name);
                            opt.text(this.price);
                            $('#products').append(opt);
                        });
                    }
            });
        })
</script>

I'm getting a response from this but I'm not seeing a any JSON. I'm using firebug. I can see there has been a JSON encoded response but the response tab is emtyp and my select boxes have no options.

Can anyone see and problems with my code?

Here is the response I should get (and do get when I run the script manually via the browser):

[{"price":"82.9230","name":"Dummy"},{"price":"177.0098","name":"Dummy 2"},{"price":"76.0208","name":"Dummy 3"},{"price":"470.6054","name":"Dummy 4"},{"price":"357.0083","name":"Dummy Product 5"}]

Thanks,

Billy

jQuery.ajax参数中添加dataType: 'json'

use cache: false , as one of your AJAX parameters...

I know when i used JSON in AJAX, i had to do this:

                    success: function(data) {
                      $(".custName, .projectDesc").empty();
                      for(var x in data) {
                         $(".custName").append(data[x].message1);
                         $(".projectDesc").append(data[x].message2);
                    }

I'm not sure if this will help you or not :)

The PHP you're returning is not an array of objects, which is the way you are treating it in your javascript.

Change your PHP to:

$products = array();
foreach( $collection as $product ) {
  $products[] = array( "price" => $product->getPrice(),
                       "name" => $product->getName() );
}

This should return JSON that looks like:

[{"price":"82.9230","name":"Dummy"},{"price":"177.0098","name":"Dummy 2"}, etc ]

jQuery.each should then be able to iterate over the returned array of objects:

success: function(products) 
{
  jQuery.each(products,function()
       {

       var opt = jQuery('<option />'); 
          opt.val(this.name);
          opt.text(this.price);
          jQuery('#products').append(opt); 
       });
  }
$.each(products,function(index, arr)
{
      var opt = $('<option />');
      opt.val(arr[name]);
      opt.text(arr[price]);
      $('#products').append(opt);
});

I hope it helps you

Try to add data type property on $.ajax configuration object:

<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: "GET",
            url: "http://localhost.com/magento/modules/products/get.php",
            dataType : 'json',
            success: function(products) {
                $.each(products,function() {
                    var opt = $('<option />');
                    opt.val(this.name);
                    opt.text(this.price);
                    $('#products').append(opt);
                });
            }
        });
    })
</script>

Maybe, $.ajax function doesn't know the response data type...

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