简体   繁体   English

跨域Ajax POST到Web-API始终返回空响应

[英]cross domain ajax POST to web-api always return empty response

I want to POST HTML form to web-api. 我想将HTML表单发布到web-api。

If I execute ajax POST with jQuery in other domain everything is OK and I receive 200 OK but in firebug and response tab I receive blank response like below image. 如果我在其他域中使用jQuery执行ajax POST,一切正常,我收到200, 在firebug和response选项卡中,我收到空白响应,如下图所示。 this is my jQuery code: 这是我的jQuery代码:

var formData = new FormData($('form')[0]);
                var response = '';
                $.ajax({
                    url: 'http://localhost:2143/api/controller',
                    type: 'POST',
                    // Form data
                    data: formData,
                    //Options to tell JQuery not to process data or worry about content-type
                    cache: false,
                    contentType: false,
                    processData: false,
                    success : function(text)
                     {
                         response = text;
                         alert(response);
                     }
                });

Please help me... 请帮我...

Due to the same origin policy restriction that's built in browsers it is not allowed to perform cross domain AJAX calls. 由于浏览器内置的same origin policy restriction ,因此不允许执行跨域AJAX调用。 You have a couple of possiblre workarounds: 您有几种可能的解决方法:

  1. JSONP - The idea here is that your server will wrap the JSON response in a callback. JSONP这里的想法是您的服务器将JSON响应包装在回调中。 This works only with GET requests, so it might not be suitable for your case from what I can see you are attempting to send a POST request. 这仅适用于GET请求,因此从您试图发送POST请求的角度来看,它可能不适合您的情况。 You could use a custom JsonpMediaTypeFormatter as shown in this similar post . 您可以使用自定义JsonpMediaTypeFormatter ,如this similar post所示。
  2. CORS - the server should send a special Access-Control-Allow-Origin response HTTP headers. CORS服务器应发送特殊的Access-Control-Allow-Origin响应HTTP标头。 The drawback here is that older browsers might not support it. 缺点是较旧的浏览器可能不支持它。 Here's a blog post covering this in more details. 这是一篇blog post涵盖了更多详细信息。
  3. Server side bridge. 服务器端网桥。 If the previous 2 techniques didn't work for you because of the constraints they are imposing you could have a server side script on the domain hosting your javascript that will act as a proxy between your domain and the remote domain hosting the API. 如果前两种技术由于约束而对您不起作用,则可能是您在托管JavaScript的域上有一个服务器端脚本,该脚本将充当您的域和托管API的远程域之间的代理。 In this case you will send the AJAX request to your own domain which in turn will call the remote API and return the result to the client. 在这种情况下,您会将AJAX请求发送到您自己的域,该域将依次调用远程API并将结果返回给客户端。

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

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