Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest cannot load an URL with jQuery

I'm trying to get some json data from a "remote" website. I run my web service on the 99000 port then, I launch my website on the 99001 port (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 launch my web page as an HTML file, I get this:

    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 try to catch the data items like this:

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'm getting this error?

like image 355
Zakaria Avatar asked Sep 30 '10 08:09

Zakaria


2 Answers

You can't do a XMLHttpRequest crossdomain, the only "option" would be a technique called JSONP, which comes down to this:

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

The other easy way out, would be to create a "proxy" on your local server, which gets the remote request and then just "forwards" it back to your javascript.

edit/addition:

I see jQuery has built-in support for JSONP, by checking if the URL contains "callback=?" (where jQuery will replace ? with the actual callback method). But you'd still need to process that on the remote server to generate a valid response.

like image 114
CharlesLeaf Avatar answered Oct 17 '22 12:10

CharlesLeaf


In 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);     } }) 
like image 23
3 revs, 2 users 88% Avatar answered Oct 17 '22 12:10

3 revs, 2 users 88%