working with JSON data array from Ajax response?

后端 未结 5 1666
一个人的身影
一个人的身影 2020-12-21 21:26

Is it possible to work with a response from AJAX request in PHP? I am not really a JS dev so i am polling my hair out with this one.

I have sort of hacked this toget

相关标签:
5条回答
  • 2020-12-21 21:38
    $('input[name=\'product_attribute[' + attribute_row + '][name]\']').catcomplete({
        delay: 0,
        source: function(request, response) {
            $.ajax({
                url: 'index.php?route=catalog/attribute/autocomplete&token=<?php echo $token; ?>',
                type: 'POST',
                dataType: 'json',
                data: 'filter_name=' +  encodeURIComponent(request.term),
                success: function(data) {   
                    response($.map(data, function(item) {
                        return {
                            category: item.attribute_group,
                            label: item.name,
                            value: item.attribute_id
                        }
                    }));
                }
            });
        }, 
        select: function(event, ui) {
            $('input[name=\'product_attribute[' + attribute_row + '][name]\']').attr('value', ui.item.label);
            $('input[name=\'product_attribute[' + attribute_row + '][attribute_id]\']').attr('value', ui.item.value);
    
            return false;
        }
    });
    

    You Can map your json something like this

    0 讨论(0)
  • 2020-12-21 21:41

    use

    dataType: 'json',
    

    instead

    dataType: 'html',
    

    and then use each to fetch the record from response in success function

    0 讨论(0)
  • 2020-12-21 21:45

    Use $.parseJSON() For Convert Json Format Data To Array

    Right code at sucess of ajax.. Like,

    var data = $.parseJSON(html);

    data in you get array format of responce

    0 讨论(0)
  • 2020-12-21 21:49

    Do like this.

    var data = $.parseJSON("your_json");
    var output= "<ul>";
    
    for (i=0; i < data.payments.length; i++){
        output += "<li>" + data.payments[i].id + ", " + data.payments[i].child_id + "</li>";
    }
    
    output += "</ul>";
    
    0 讨论(0)
  • 2020-12-21 21:51

    You need to use json_encode() in your php file to send the data back as an array

    For example;

    $myarray = array("data1"=>"value1","data2"=>"value2");
    
    echo json_encode($myarray);
    

    You can then access the data separately in the js file like this;

     success: function(html) { 
        alert(html.data1);
        alert(html.data2);
      },
    

    You also need to change the dataType to 'json'

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