简体   繁体   中英

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

I want to POST HTML form to 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. this is my jQuery code:

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. You have a couple of possiblre workarounds:

  1. JSONP - The idea here is that your server will wrap the JSON response in a callback. 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. You could use a custom JsonpMediaTypeFormatter as shown in this similar post .
  2. CORS - the server should send a special Access-Control-Allow-Origin response HTTP headers. The drawback here is that older browsers might not support it. Here's a blog post covering this in more details.
  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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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