XMLHttpRequest cannot load url using jQuery

I am trying to get some json data from the "remote" website. Then I launch my web service on port 99000, I launch my site on port 99001 (http: // localhost: 99001 / index.html).

I get the following message:

XMLHttpRequest cannot load http://localhost:99000/Services.svc/ReturnPersons. Origin http://localhost:99001 is not allowed by Access-Control-Allow-Origin. 

Even if I run my webpage as an HTML file, I get the following:

  XMLHttpRequest cannot load http://localhost:99000/Services.svc/ReturnPersons.Origin null is not allowed by Access-Control-Allow-Origin. 

The web service returns data. I am trying to catch data items as follows:

 var url = "http://localhost:99000/Services.svc/ReturnPersons"; $.getJSON(url, function (data) { success: readData(data) }); function readData(data) { alert(data[0].FirstName); } 

And I'm trying to get this structure:

 [{"FirstName":"Foo","LastName":"Bar"},{"Hello":"Foo","LastName":"World"}] 

Do you know why I get this error?

+55
json jquery cors cross-domain
Sep 30 '10 at 8:31
source share
5 answers

You cannot use crosshain XMLHttpRequest, the only "option" will be the JSONP method, which boils down to the following:

To start the request: add a new <script> with the remote URL, and then make sure the remote url returns a valid javascript file that calls your callback function. Some services support this (and allow you to call your callback in GET parameters).

Another simple way would be to create a โ€œproxyโ€ on your local server that will receive the remote request and then simply โ€œredirectโ€ it back to your javascript.

edit / add:

I see that jQuery has built-in JSONP support by checking if the url contains "callback =?" (where jQuery will replace? with the actual callback method). But you still have to process this on the remote server in order to create the correct answer.

+39
Sep 30 '10 at 8:34
source

In the new jQuery 1.5 you can use:

 $.ajax({ type: "GET", url: "http://localhost:99000/Services.svc/ReturnPersons", dataType: "jsonp", success: readData(data), error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }) 
+33
Feb 10 '11 at 2:57
source

A script with 3 working solutions in action.

For external JSON:

 myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json' 

Solution 1: $ .ajax () + jsonp:

 $.ajax({ dataType: "jsonp", url: myurl , }).done(function ( data ) { // do my stuff }); 

Solution 2: $ .ajax () + json + & calback = ?:

 $.ajax({ dataType: "json", url: myurl + '&callback=?', }).done(function ( data ) { // do my stuff }); 

Solution 3: $ .getJSON () + calback = ?:

 $.getJSON( myurl + '&callback=?', function(data) { // do my stuff }); 

Documentation: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/

+19
Apr 01 '13 at 16:26
source

A possible workaround was discovered that I don't think was mentioned.

Here is a good description of the problem: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Basically, as long as you use forms with forms / URL-encoded / text texts, you're fine.

 $.ajax({ type: "POST", headers: { 'Accept': 'application/json', 'Content-Type': 'text/plain' }, dataType: "json", url: "http://localhost/endpoint", data: JSON.stringify({'DataToPost': 123}), success: function (data) { alert(JSON.stringify(data)); } }); 

I use it with ASP.NET WebAPI2. So, on the other end:

 public static void RegisterWebApi(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); } 

Thus, Json formatting is used when analyzing the type of text content.

And don't forget in Web.config:

 <system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Methods" value="GET, POST" /> </customHeaders> </httpProtocol> 

Hope this helps.

+6
Feb 03 '14 at 21:02
source

I am using WebAPI 3 and encountered the same problem. The problem is resolved because @Rytis added his own solution. And I think that in WebAPI 3 we do not need to define the RegisterWebApi method.

My change was only in the web.config file and it works.

 <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Methods" value="GET, POST" /> </customHeaders> </httpProtocol> 

Thanks for the solution @Rytis!

0
Nov 23 '16 at 17:27
source



All Articles