Guillaume le Floch
Guillaume le Floch

Reputation: 1083

Jsonp cross-domain ajax

I'm working on an application which use ajax call to get html from the server. When I run it on the server, everything works fine.

But when I'm running on a localhost, I've a 'Access-Control-Allow-Origin' error. I looked arround and it seems like using jsonp could be the solution.

So, my ajax call looks like that:

$.ajax({
    url: url,
    dataType: 'jsonp',
    crossDomain: true,
    type: 'GET',
    success: function(data){
        // should put the data in a div
    },
    error: function(){
        //do some stuff with errors
    }
});

I get html from the server, but I always have this error:

Uncaught SyntaxError: Unexpected token < 

Is there a way to wrap the jsonp response in html?

Thanks!

Upvotes: 0

Views: 809

Answers (2)

Pete
Pete

Reputation: 2558

You can't use JSONP to grab an HTML document. You need to wrap your HTML in a JavaScript variable. JSONP has some very specific requirements to make it work properly, including a callback function/attribute. If you're not in control of the server hosting the target page, you won't be able to make it work. This is a security precaution to prevent a random page from being able to steal your personal information from sites you're logged into via an AJAX call.

UPDATE

I read your question more thoroughly. It sounds like your problem is that you're in a development environment that doesn't have the resource in question. JSONP isn't the answer because it's a lot of trouble to get running just to make your page work in development. You should create a local copy of the target HTML and grab it using a relative or server-absolute URL such as "/the/page/i/need.html" instead of "http://myserver.com/the/page/i/need.html"

Upvotes: 2

xdazz
xdazz

Reputation: 160833

If you want to get the data by jsonp, then the server side need to support jsonp.

There is no way just change the dataType to get the data.

If the server side doesn't support jsonp, then you need to make a proxy in your localhost.

Upvotes: 1

Related Questions