简体   繁体   中英

Parse json from php in js

I have array in my php file:

    $invoices_arr = [];

    foreach ($invoices as $key=>$invoice){
    $invoices_arr[$key]['id']=$invoice->get_id();
    $invoices_arr[$key]['code_text']=$invoice->get_code_text();
    $invoices_arr[$key]['invoice_name']=$invoice->get_invoice_name();
    $invoices_arr[$key]['status_invoice']=$invoice->get_status_invoice();
    $invoices_arr[$key]['attachments']=$invoice->get_attachments();
}
echo json_encode(['invoices'=>$invoices_arr]);

My ajax call:

 $.ajax({
                data:{lead_id:$("#lead_id").val()},
                url: sJSUrlGetAllLeadInvoices,
                success: function (data) {
                    var obj = jQuery.parseJSON(data);
                    $("#all_invoice_table tbody").empty();


                    $(obj.invoices).each(function(key,value){
                        $('#all_invoice_table').append('<tr><td>'+value.invoice_name+'</td><td class="invoice_status">'+value.status_invoice+'<td>attt</td><td><button id="'+value.id+'" class="edit_invoice_'+value.id+'">Edit invoice</button</td><td><button class="send_invoice_btn_'+value.id+'">Send invoice</button></td><td><img class="delete_invoice_'+value.id+'" src="/images/icons/delete.gif"></td><td class="invoice_hidden_column_'+value.id+'">'+value.code_text+'</td></tr>');
 });
   }
    });

In field value.attachments there is php serialize array, for example, string "a:1:{i:0;s:36:"../../pdf_invoices/2017-10-10015.pdf";}" . How can I convert this string to array in js?

I try do it:

       var mas=JSON.parse(value.attachments);

But I get error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

How can I solve it? Thanks for any help.

也许您应该在JSON中进行编码之前先在PHP代码中反序列化

You don't need to parse the result with jQuery.parseJSON because jQuery do it for. If you inspect data using console.log() you will see that is a Javascript object ready for to use.

You need to pass datatype as json. you can use jQuery parse method for parsing json response.

datatype:json

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