如何将发布/获取json值(html)发送到API?

时间:2019-05-08 09:06:36

标签: javascript html json

Javascript / HTML的新功能。所以,请对我轻松一点!

我现在在脚本中所做的是,我创建了一个具有不同值选项的表单,用户可以在其中输入他们的输入。用户点击提交后。我完成了一个检查该值中的一个是否实际具有值的函数,如果没有,请重试。如果有值,那么我们继续,现在我做了一个简单的事情,将值保存为json格式。

<script src="FileSaver.js"></script>

<script>

function myFunction() {
  var inpObj = document.getElementById("namn");
  if (!inpObj.checkValidity()) {
    document.getElementById("toggle").innerHTML = inpObj.validationMessage;
  } else {
    document.getElementById("toggle").innerHTML = "Tack för beställning";

    var data = {'name': name.value, 'flask': flask.value, 'kyckling': kyckling.value, 'anka': anka.value, 'kalkon': kalkon.value, 'leverans': leverans.value, 'ovrigt':ovrigt.value}
    var json = JSON.stringify(data)
    var blob = new Blob([json],{type:"application/json"});
    saveAs(blob,"helloworld.json");
  } 
} 

</script>

我现在要做的是将值var data发送到POST / GET Api,它将读取json格式,然后将文件保存到json(通过C#服务器) 。但是,我尝试进行搜索,但还没有真正找到一种将值(JSON)发送到API的方法。

我将不胜感激!

完整的HTML + Javascript + Filesaver

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Hello</title>

  <link rel="icon" href="img/favicon.png" type="image/png">
  <link rel="stylesheet" href="vendors/bootstrap/bootstrap.min.css">
  <link rel="stylesheet" href="vendors/fontawesome/css/all.min.css">
  <link rel="stylesheet" href="vendors/linericon/style.css">
  <link rel="stylesheet" href="vendors/nice-select/nice-select.css">

  <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <!-- ================ header section start ================= -->    
    <header class="header_area">
    <div class="header-top">
      <div class="container">
        <div class="d-flex align-items-center">
          <div id="logo">
            <a href="index.html"><img src="img/Logo.png" alt="" title="" /></a>
          </div>
        </div>
      </div>
    </div>


  </div>
</header>
<!-- ================ header section end ================= -->  

<main class="site-main">


  <!-- ================ start banner area ================= --> 
  <section class="home-banner-area" id="home">
    <div class="container h-100">
      <div class="home-banner">
        <div class="text-center">
          <h1>handlingslist</h1>
        </div>
      </div>
    </div>
  </section>
  <!-- ================ end banner area ================= -->


  <!-- ================ start banner form ================= --> 
  <form class="form-search form-search-position">
    <div class="container">
      <div class="row">
        <div class="col-sm gutters-19">
          <div class="form-group">
            <label for="FormControlSelect1">Handlingslist Namn</label>
            <input class="form-control" id="namn" type="text" placeholder="Skriv in namn.." required>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-sm gutters-19">
          <div class="form-group">
            <label for="exampleFormControlSelect1">Fläsk</label>
            <select class="form-control" id="flask">
              <option>0</option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-sm gutters-19">
          <div class="form-group">
            <label for="exampleFormControlSelect1">Kyckling</label>
            <select class="form-control" id="kyckling">
              <option>0</option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-sm gutters-19">
          <div class="form-group">
            <label for="exampleFormControlSelect1">Anka</label>
            <select class="form-control" id="anka">
              <option>0</option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-sm gutters-19">
          <div class="form-group">
            <label for="exampleFormControlSelect1">Kalkon</label>
            <select class="form-control" id="kalkon">
              <option>0</option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
            </select>
          </div>
        </div>
      </div>



      <div class="row">
        <div class="col-sm gutters-19">
          <div class="form-group">
            <div class="form-select-custom">
              <label for="exampleFormControlSelect1">Leverans</label>
              <select name="" id="leverans">
                <option value="8 AM">8:00</option>
                <option value="12 PM">12:00</option>
                <option value="6 PM">18:00</option>
                <option value="9 PM">21:00</option>
              </select>
            </div>
          </div>
        </div>  
      </div>
      <div class="row">
        <div class="col-sm gutters-19">
          <div class="form-group">
            <label for="exampleFormControlSelect1">För övriga information, vänligen och informera...</label>
            <input class="form-control" id="ovrigt" type="text" placeholder="Enter your keywords..">
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-sm gutters-19">
          <div class="form-group">
            <button class="button button-form" id="toggle" onclick="myFunction()" type="submit">Beställning</button>
          </div>
        </div>
      </div>
    </div>
  </form>
  <!-- ================ end banner form ================= --> 


</main>



<!-- ================ start footer Area ================= -->
<footer class="footer-area section-gap">
  <p class="col-md-15 text-center">
  Copyright &copy; 2019 All rights reserved | Made by Thrill</a>
</div>
</div>
</footer>
<!-- ================ End footer Area ================= -->

<script src="FileSaver.js"></script>

    <script>

  function myFunction() {
    var inpObj = document.getElementById("namn");
    if (!inpObj.checkValidity()) {
      document.getElementById("toggle").innerHTML = inpObj.validationMessage;
    } else {
      document.getElementById("toggle").innerHTML = "Tack för beställning";

      var data = {'name': test.value, 'flask': flask.value, 'kyckling': kyckling.value, 'anka': anka.value, 'kalkon': kalkon.value, 'leverans': leverans.value, 'ovrigt':ovrigt.value}
      var json = JSON.stringify(data)
      var blob = new Blob([json],{type:"application/json"});
      saveAs(blob,"helloworld.json");

      fetch(url, {
        method: 'POST', // or 'PUT'
        body: JSON.stringify(data), // data can be `string` or {object}!
        headers:{
          'Content-Type': 'application/json'
        }
      }).then(res => res.json())
      .then(response => console.log('Success:', JSON.stringify(response)))
      .catch(error => console.error('Error:', error));

    } 
  } 

</script>

<script src="vendors/jquery/jquery-3.2.1.min.js"></script>
<script src="vendors/bootstrap/bootstrap.bundle.min.js"></script>
<script src="vendors/easing.min.js"></script>
<script src="vendors/superfish.min.js"></script>
<script src="vendors/nice-select/jquery.nice-select.min.js"></script>
<script src="vendors/jquery.ajaxchimp.min.js"></script>
<script src="vendors/mail-script.js"></script>
<script src="js/main.js"></script>
</body>
</html>

我的目标是能够将值var data发送到API。 我相信。...

3 个答案:

答案 0 :(得分:1)

基本上,您正在尝试进行一次休息电话,有很多方法可以执行此操作,如果您不想使用nay库(例如jquery),则可以使用fetch api

fetch(`Your_server_url`, {
    method: "POST", //OR GET
    mode: "cors", // If your page and your API server is in differnet location

    headers: {
    "Content-Type": "application/json",// because you are sending JSON data
    },
    body: JSON.stringify(data), // your tata 
})
.then(response => {
    console.log(response);
}); 

您可以了解如何获取here

答案 1 :(得分:0)

这是一个Ajax示例:

$.ajax({
    data: {varRecibed:varSended},
    type: "POST",
    url: "the-url-api",
    dataType: "json",
    beforeSend: function(){
        //Action before send info
    },
    success: function(data){
        //When api finish, data is the returning info from the api.
        console.log(data);      
    }
});

参考:http://api.jquery.com/jquery.ajax/

@amn 是正确的,您需要包括 jQuery library才能使用$.ajax https://jquery.com/download/

答案 2 :(得分:0)

这是执行到服务器的POST的功能:

function post (path, data) {
  return window.fetch(path, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })

然后您像这样调用此函数:

post('/url', {data, data1});