使用REST API并发送POST请求

时间:2016-07-10 09:41:57

标签: javascript jquery html json

POST localhost:5000/registrar

{
  "enrollId": "jim",
  "enrollSecret": "6avZQLwcUe9b"
}

如何在javascript文件中使用它?我使用JSON还是JQuery?我如何在.html中调用请求函数?

1 个答案:

答案 0 :(得分:5)

使用jquery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

并调用函数

$(document).ready(function(){

    $.post('localhost:5000/registrar', {
      "enrollId": "jim",
      "enrollSecret": "6avZQLwcUe9b"
    }, function(serverResponse){

    //do what you want with server response

    })

})

同样没有简写来处理错误:

$.ajax({
  type: "POST",
  url: 'localhost:5000/registrar',
  data: {
      "enrollId": "jim",
      "enrollSecret": "6avZQLwcUe9b"
    },
  success: function(){$('#register').html('<h1>Login successfull</h1>');},
  error: function(){$('#register').html('<h1>Login error</h1>');},
  dataType: dataType
});