简体   繁体   English

如何通过Ajax调用使用剩余的Web服务

[英]How to consume rest web service from ajax call

I want to call my rest web service from ajax. 我想从ajax调用我的其余Web服务。 Url for my service is ' https://scv-dev.com/cdcAug/surveys/surveyData '. 我的服务网址是“ https://scv-dev.com/cdcAug/surveys/surveyData ”。 Iam able to call this service from rest client (firefox browser) but when am trying to call from ajax am getting error. 我可以从其他客户端(firefox浏览器)调用此服务,但是尝试从ajax调用时却出错。

Ajax call : Ajax通话:

$.ajax({
     type: "POST",
     url: "https://scv-dev.com/cdcAug/surveys/surveyData",
     data: JSON.stringify({surveyId:1}),
     dataType: "json",
     headers: {
            Accept: "application/json",
            "Access-Control-Allow-Origin": "*"
        },
     success: function (data) {
          alert(1);
     },

     error: function (jqXHR) {            
          alert(2);
     }

 });

Below is code for webs service : 以下是网站服务的代码:

@RequestMapping(value = "/surveyData", method = RequestMethod.POST, headers = "Accept=application/json")
public @ResponseBody
SurveyDataResponse getSurveyData(@RequestBody SurveyResApp surveyResApp,
        final HttpServletResponse httpResponse) {
            ..............
        }

You appear to be confused about Access-Control-Allow-Origin: * . 您似乎对Access-Control-Allow-Origin: *感到困惑。 That is something the server returns, not something the client sets. 那是服务器返回的东西,而不是客户端设置的东西。

It appears that you have a same-origin access error and looking in the browser error log or diagnosing the returned error codes should tell you what exactly is going on. 看来您有一个同源访问错误,在浏览器错误日志中查找或诊断返回的错误代码应该可以告诉您发生了什么事情。

You probably need to enable your web service for cross origin access by adding that header Access-Control-Allow-Origin: * to your server response. 您可能需要通过将标头Access-Control-Allow-Origin: *到服务器响应中来启用Web服务以进行跨源访问。 See here for an example. 请参阅此处的示例。

I created filter class added below code in that to add "Access-Control-Allow-Methods" in response. 我创建了在下面的代码中添加的过滤器类,以在响应中添加“ Access-Control-Allow-Methods”。

response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
    response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
    response.addHeader("Access-Control-Max-Age", "1728000");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM