使用 Jquery POST 以休息 api

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20143256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:59:57  来源:igfitidea点击:

POST to rest api using Jquery

jqueryrest

提问by bookthief

I'm writing a function to post data from a form to a rest api. This is what I have but it's not working and I cant figure out why.

我正在编写一个函数来将数据从表单发布到休息 api。这就是我所拥有的,但它不起作用,我不知道为什么。

<script>
    console.log(document);
    var form = document.getElementById("myform");

    form.onsubmit = function (e) {
      // stop the regular form submission
      e.preventDefault();

      // collect the form data while iterating over the inputs
      var data = {};
      for (var i = 0, ii = form.length; i < ii; ++i) {
        var input = form[i];
        if (input.name) {
          data[input.name] = input.value;
        }
      }

    function addData(){
     $.ajax({
             type: "POST",
             url: "http://example.com",
             data: JSON.stringify(data),
             contentType: "application/json; charset=utf-8",
             crossDomain: true,
             dataType: "json",
             success: function (data, status, jqXHR) {

                 alert(success);
             },

             error: function (jqXHR, status) {
                 // error handler
                 console.log(jqXHR);
                 alert('fail' + status.code);
             }
          });
    }
</script>

Can anyone point me in the right direction?

任何人都可以指出我正确的方向吗?

采纳答案by Murali Murugesan

You are not calling addData()in form.onsubmitevent.

你不是addData()在打电话form.onsubmit

form.onsubmit = function (e) {
  // stop the regular form submission
  e.preventDefault();

  // collect the form data while iterating over the inputs
  var data = {};
  for (var i = 0, ii = form.length; i < ii; ++i) {
    var input = form[i];
    if (input.name) {
      data[input.name] = input.value;
    }
  }
  addData();
}

回答by Rituraj ratan

calllike below

调用如下

addData(data);

function addData(data){// pass your data in method
     $.ajax({
             type: "POST",
             url: "http://example.com",
             data: JSON.stringify(data),// now data come in this function
             contentType: "application/json; charset=utf-8",
             crossDomain: true,
             dataType: "json",
             success: function (data, status, jqXHR) {

                 alert("success");// write success in " "
             },

             error: function (jqXHR, status) {
                 // error handler
                 console.log(jqXHR);
                 alert('fail' + status.code);
             }
          });
    }