如何使用jQuery或任何其他东西从REST调用格式化JSON / XML答案?

时间:2016-04-22 15:54:03

标签: jquery json xml rest

我有一个HTML来调用REST Web服务并获得JSON / XML答案。 我必须做些什么才能以可读的方式得到答案? 我可以使用一些ajax来刷新页面吗?怎么样?

我的HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Specify Parameters</title>

  <script>
    function execute() {
      var param1 = $("#param1").val();
      var param2 = $("#param2").val();
      var format = $('input:radio[name=format]:checked').val();
      var url = "http://localhost/something?rs=" + param1 + "|" + param2
              + "&format=" + format;

      location.href = url;
    }
  </script>

</head>
<body>

<div id="mainDiv">   

    <div class="param1">
    <label for="param1">Param1:</label>
    <input type="text" id="param1" size="10" value="514" />
   </div>   

   <div class="param2">
    <label for="param2">Param2:</label>
    <input type="text" id="param2" size="10" value="PI761" />
   </div> 

<div id="radioButtonsDiv">
     <input type="radio" name="format" value="json" checked>JSON
     <input type="radio" name="format" value="xml">XML
</div>

<div class="submitDiv"><input type='button' id='submit' onClick='execute()' value="Submit"/><div class="submitDiv"> 

</div>

</body>
</html>

回应示例:

{
    "result": [{
        "string01": "104",
        "string02": "104 - blablabla",
        "string03": "104",
        "string04": "blobloblo",
        "string05": "blablabla",
        "dest": [{
            "pred": [{
                "time": 1461348846,
                "sec": 102,
                "min": 1,
                "string11": "514-String",
                "string12": "Some String",
                "string13": "Some other String",
                "number": 0
            }]
        }]
    }]
}

1 个答案:

答案 0 :(得分:-1)

我使用jQuery得到了HTML格式的输出:

$.getJSON(URL, function(data) {
    $('#divname').html(data.result[0].string05 + ',' + data.result[0].dest[0].pred[0].time);
})

HTML:

<div id="divname"></div>