2012-03-21 2 views
2

私は、関数の出力を取得するにはワードプレスでAJAXを使用しています:ajaxで複数の出力を取得するには?

jQuery.ajax({ 
      type: "POST", 
      url:"wp-admin/admin-ajax.php", 
      data:'action=nafham_list_cats_selection&selection_id=' + $selection_id, 
      success:function(results){ 
       jQuery(".semester_selection").empty(); 
       jQuery(".semester_selection").prop('disabled', false); 
       jQuery(".semester_selection").append(results); 
      } 
     }) 

そして、ここでは、私が使用する機能です。

function nafham_list_cats_selection() { 
    if(isset($_POST['selection_id'])){ 
     nafham_get_listed_cats($_POST['selection_id']); 
     die(); 

    } 
} 

jQueryのAJAXを使用して、私はの出力を得ることができますよ私は関数が2つの変数をエコーする場合、私は2つの値をajaxレスポンスで区切って使うことができるように、それは可能ですか?

+3

JSONを試しましたか? – jprofitt

+1

serialize ...または複数の出力を1つの – zod

+1

Fyiに連結すると、クエリ文字列を手動で構築するのではなく、オブジェクトを 'data'として渡すことができます。そして、あなたは 'jQuery'を長い形式で一度書く必要があることを知りましたか?あなたのコードを '(function($){....})(jQuery);'にラップすることによって、 'noConflict'が使われていても' $ 'を使うことができます。 – ThiefMaster

答えて

4

あなたは

// Some code here and finally you've an array to echo/send to the browser i.e. 
$data=array("id"=>1, "text"=>"This is some content"); // This is your data array/result 
echo json_encode($data); // use json_encode to convert it to json encoded string 

コードの上にあなたのphpファイルを持っている場合は、ブラウザあなたのAjaxの成功コールバックで

{"id":1,"text":"This is some content"} 

に次のJSONエンコードされた文字列を送信します例えば、あなたの出力の配列を作ります'parseJSON'を使用してjsonオブジェクトに変換することができます。

jQuery.ajax({ 
     type: "POST", 
     url:"wp-admin/admin-ajax.php", 
     data:'action=nafham_list_cats_selection&selection_id=' + $selection_id, 
     success:function(results){ 
      var obj=$.parseJSON(results); // now obj is a json object 
      alert(obj.id); // will alert "1" 
      alert(obj.text); // will alert "This is some content" 
     } 
    }); 

あなたが理解するのを手伝ってくれる一例と希望。詳細についてはthisthisをお試しください。

関連する問題