如何在ajax中访问数组的一部分


How to access part of an array in ajax

在我的ajax中,PHP端包含一个包含3个值的数组。我想把这3个值放入单独的输入字段。我该怎么做呢?如何访问从PHP发送的数组?

我的代码:

PHP

    $total['tot1'] = $numwelds + $numconwelds + $mpcountrys ;
    $total['tot2'] = $numwelds + $numconwelds + $fortot2 ;
    $total['tot3'] = $numwelds + $numconwelds + $fortot2 / $fortot3; 
    $response = json_encode($total);
    header("Content-Type: application/json");  
    echo $response;
    exit;
Jquery

 jQuery(document).ready( function($) {
        (function($) {
        $(document).ready(function(){
           $('#formsubmit').click(function(){
          $.post(
          PT_Ajax.ajaxurl,
                {
               action : 'ajax-inputtitleSubmit',
               numberofwelds : $('input[name=numberofwelds]').val(),
               numberofconwelds : $('input[name=numberofconwelds]').val(),
               nextNonce : PT_Ajax.nextNonce
                },
          function( response ) {
              $("#totalone").val(response);
               $("#totaltwo").val(response);
                $("#totalthree").val(response);
                }
                );
              return false;
        }); 
        });
        })(jQuery);
        });

您可以使用JSON.parse将json转换为对象:

var obj = JSON.parse(response);
$("#totalone").val(obj.tot1);
$("#totaltwo").val(obj.tot2);
$("#totalthree").val(obj.tot3);

或者你也可以使用jQuery的$.parseJSON()

use like

$("#totalone").val(response["tot1"]);
$("#totaltwo").val(response["tot2"]);
$("#totalthree").val(response["tot3"]);