【问题标题】:Unable to perform ajax api call无法执行 ajax api 调用
【发布时间】:2020-01-07 12:40:15
【问题描述】:

我的 html 页面在下面指定的 url 上运行,从我的 html 页面中,我想通过单击按钮来点击我的 rest api 控制器。但是由于没有调用 api 并且主 spring boot 应用程序在 http 端口 8080 上成功启动,因此出现错误。

网址

file:///C:/Users/PF077060/Downloads/project/project/UI%20design/html/Release.html

Ajax 代码:


<script >
$(document).ready(function(){
    $("#btn").click(function(event){
        event.preventDefault();
        alert("AJAX request successfully completed");


        ajaxpost();
      });
      function ajaxpost()
      {
          console.log("formData1");  
          var formdata=
          {
                  name:$("#name").val(),
                inputcutoff:$("#inputcutoffdate").val(),
                releasedate:$("#releaseDate").val(),
                    status:$("#status").val(),                  
          };
          //alert("Changed into json format");
          console.log(formdata);
          $.ajax({
              type : "POST",
              contentType : "application/json", 
              url : "localhost:8080/" + "release/addrelease/",
              data : formdata,
              success : function(result)
              {
                alert(result.name);  
                window.location="Main.html";

              },
              error : function(e)
              {
                  alert("Error");
                  console.log("ERROR: ",e);
              }
         });
         resetdata();
      }
      function resetdata(){
          $("#name").val("");
          $("#inputcutoffdate").val("");
          $("#releaseDate").val("");
          $("#status ").val("");
      }
    });
</script>

错误

CORS 策略已阻止从源“null”访问“localhost:8080/release/addrelease/”处的 XMLHttpRequest:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https .

任何帮助将不胜感激

【问题讨论】:

标签: ajax rest


【解决方案1】:

出现此错误是因为在控制器类中未指定 CrossOrigin 注释,并且 Ajax 调用中的 url 必须以 http:localhost:8080 等开头。

**In the controllers**
@Crossorigin(origin="*")


**In the ajax call**
url: "http\localhost:8080\\{url were user want to get connected}"

那么 API 不应该返回 null 值,API 的工作是始终处理信息并应该返回一些值给客户端。 这些是我所做的更改,我的 ajax 调用也成功了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多