将HTML表转换为Json数据并将数据传递给jquery中的ajax调用

时间:2018-08-25 06:49:19

标签: jquery json ajax

我必须将HTML表转换为json数据,并将其传递给ajax调用。 如何在Ajax中将json数据作为参数传递。如果值为字符串,则传递数据,而当其为json格式时,则不传递数据。

<script type="text/javascript">  
$(document).ready(function () {
            $('#btnSumbitTime').click(function () {        
              $('#result').append(JSON.stringify(makeJsonFromTable('tblSelectTime')))
                $('#result').show()
                alert(JSON.stringify(makeJsonFromTable('tblSelectTime')));
   This is my json data after converting from html table           
var selectedTime = "{[{\"Select\":\"\",\"FromTime\":\"\",\"ToTime\":\"\"},{\"Select\":\"\",\"FromTime\":\"11:02\",\"ToTime\":\"15:02\"}]}";

                $.ajax({
                    type: "POST",
                    url: '../AotuComplete.asmx/GetSeletedTime',
                    data: {SelectedTime: JSON.stringify(selectedTime) },
                    contentType: "application/j-son;charset=UTF-8",
                    dataType: "json",
                    success: function (response) {
                        alert(response.d);
                    }
                })
            })
        });
 </script>

1 个答案:

答案 0 :(得分:1)

检查以下代码段

function submit(){
  var keys=[], arrayObj=[];
  $("#table thead tr th").each(function(){
    keys.push($(this).html());
  });
  
  $("#table tbody tr").each(function(){
    var obj={}, i=0;
    $(this).children("td").each(function(){
      obj[keys[i]]=$(this).html();
      i++;
    })
    arrayObj.push(obj);
  });
  $('body').append(JSON.stringify({yourObj: arrayObj}));
  return;//remove this line
  $.ajax({
    type: "POST",
    url: your_url,
    data: JSON.stringify({yourObj: arrayObj}),
    contentType: "application/j-son;charset=UTF-8",
    dataType: "json",
    success: function (response) {
       alert(response.d);
    }
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>

<body>

<table id="table">
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
      <th>Expence</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
      <td>$100</td>
    </tr>
  </tbody>
  <tfoot>
  	<tr>
    	<td colspan="3">
        <button onclick="submit()"> Submit</button>
      </td>
    </tr>
  </tfoot>
</table>
</body>
</html>

  

在ajax调用之前删除return语句并修改ajax   陈述。单击提交按钮时显示的json值将为   在ajax调用中作为jsonstring传递。您可以修改密钥并   值。