簡體   English   中英

從jquery ajax獲取響應數組到php

[英]Get response array from jquery ajax to php

我試圖使用jquery ajax基於選擇框選項從mysql填充表,到目前為止這是我的jquery代碼。 我可以在警報框中顯示結果,但我不知道如何將其發送到php,這樣我就可以遍歷數組並創建表。

// selector de campaña en reporte de clientes mas activos
$(document).ready(function(){
    $('.selector-camp').change(function(){
        var campaing = $('.selector-camp').val();
        $.post( "../campanas/test", { 'camp': campaing },
        function( data ) {
            alert( data.result );
        }, "json");
    });
});

由於我使用JavaScript的方式比jquery多,因此我將用JavaScript編寫它,並且我確信您也可以在Jquery中做到這一點,但是在JavaScript中它也很容易做到

      function( data ) 
      {
        createTable(data.result); //pass your json array to JS function
      }, "json");
      //here i create js function
      function createTable(array)
      {
         var array = JSON.parse(array); //decoding from json format
         //So if i have numbers in array like [1, 2, 3, 4] and want
         //to create row with them something like this should be done
         var table = document.createElement("table"); //create table
             var tr = document.createElement("tr"); //create row
             for(var i=0; i<array.length; i++)
             {
                 var td = document.createElement("td");
                     td.innerHTML = array[i]; 
                 tr.appendChild(td); 
                 //for each array element creates cell and appends to row
              }
              table.appendChild(tr);
          //Then you can have some empty div and append table to it
          var div = //your empty div
              div.appendChild(table);
       }

請根據您的要求檢查以下php原型代碼。 從ajax請調用此文件,由於我使用了json_encode()函數,它將返回一個json響應,您也可以直接返回數組,但我不建議這樣做,也可以編輯此代碼以用於進一步的mysql查詢。

<?php 
test();
function test(){
    $camp = htmlspecialchars($_POST['camp']);
    isset($camp)&&!empty($camp)?
    $data = array('test_key'=>'test_value');
    echo json_encode($data);
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM