2014-03-25 28 views
0

在我的ajax中,PHP端包含一個包含3個值的數組。我想將這3個值放入單獨的輸入字段中。我怎樣才能做到這一點?我如何訪問PHP發送的數組?如何在ajax中訪問數組的一部分

我迄今爲止代碼:

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); 
     }); 
+1

你的jQuery是奇怪的嵌套。您已經在'document.ready'中,並且在IIFE內部打開了另一個'document.ready'?你應該拋棄''jQuery(document).ready(function($){function($){','$(document).ready'之前的所有內容) – meagar

+0

[訪問數組中的對象值](http://stackoverflow.com/questions/6650587/accessing-the-object-values-inside-an-array) – brandonscript

回答

1

您可以使用JSON.parse轉換JSON反對:

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

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

0

使用像

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