如何在html中显示通过ajax传递的数组

时间:2015-07-13 06:02:40

标签: javascript php ajax

这是我的ajax:

$("#submit").on("click",function()
    {

          $("#add_car_form").submit(function(){           
            var data = {
              "action": "test"
            };
            data = $(this).serialize() + "&" + $.param(data);
            $.ajax({
              type: "POST",
              dataType: "text",
              url: "add_car_submit.php", //Relative or absolute path to response.php file
              data: data,
              success: function(data) {

                $(".the-return").html("<br />JSON: " + data );//this outputs 
  

{ “car_name”: “; 11”, “car_maker”: “NJK”, “car_type”: “NKJ”, “通勤”: “1”, “速率”:[ “89”, “67”, “45”, “34”, “23”], “动作”: “测试”}

              }
            });
            document.getElementById("add_car_form").reset();
            return false;
          });

        });

我只是回复来自php脚本:echo $return["json"];,它将输出如下:

{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}

如何在html表格中附加这样的div?

Car Name: name
Car Maker: maker
......

2 个答案:

答案 0 :(得分:1)

您不应在点击处理程序中创建表单提交处理程序,因为它可以为单击事件创建多个侦听器。

我认为您可以在服务器端使用json_encode对数据进行编码,然后使用json接受客户端中的dataType: 'json'响应,然后

$("#submit").on("click", function () {

    var $form = $("#add_car_form")
    var data = {
        "action": "test"
    };
    data = $form.serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "add_car_submit.php", //Relative or absolute path to response.php file
        data: data,
        success: function (data) {

            $(".the-return").html("Car Name" + data.car_name + '<br />Car Maker' + data.car_maker); //Add more properties here

        }
    });
    document.getElementById("add_car_form").reset();
    return false;

});

答案 1 :(得分:1)

在你的成功函数中尝试这个

data = jQuery.parseJSON( data );  //parse data if this is text other wise use data directly. hope this is a text param in your case.
var out = '<table>';
$.each(data, function( key, value ) {
  out += '<tr><td>'+key+': '+ value +'</td></tr>';
});

out += '</table>';

//append out to your div
 $(".the-return").html(out);