Justin
Justin

Reputation: 2530

jQuery Mobile -> Load content from external server

I am working on a seemingly basic mobile app (first). But I want to enable the application to request information from our 'head' server. To make sure it has the latest information.

I'm currently running a jQuery script like this.

$.ajax({
        url: 'http://www.domain.com/list.php',
        dataType: 'json',
        crossDomain: true,
        success: function(data) {

            // Remove all content first
            $(contentId +' li').remove();

            // Load Data
            $.each(data.items, function(index, list){
                $(contentId).append('<li><a href="details.html?id=' + list.homeId + '" >' + list.name + '</a></li>\n');
            });

            // Reload View
            $(contentId).listview('refresh');

        }, 
        error: function(jqXHR, textStatus, errorThrown) {
            console.log('Error: '+ jqXHR + textStatus + errorThrown);
        }
    });

And actually on that LIST.PHP file, it does return a JSON string. But what I did for security was by adding this as a header

header("Access-Control-Allow-Origin: *");

Or I could change * to a domain/url to add better security. But if I don't add that header() code in their, my javascript breaks and won't run properly.

I guess what i'm truly wondering is, am I doing this properly? or is there a better way to do this? I have tried JSONP, but I can't seem to get that to work for cross domain.

Is my solution sound? or total crap? Any thoughts or direction would be greatly appreciated!

Upvotes: 1

Views: 900

Answers (1)

Linus Thiel
Linus Thiel

Reputation: 39231

I think you should look into JSONP. It's not that hard. On the client side, jQuery already handles it out of the box, just append a ?callback=? to the URL. On the server, instead of just responding with JSON, e.g.:

{
  "foo": "bar"
}

Look for the query parameter callback, and if it exists, wrap your JSON output in a function call with the name being the value of the callback parameter, so, for callback=foo:

foo({
  "foo": "bar"
})

When responding with JSONP, send Content-Type: text/javascript. This should work without setting Access-Control-Allow-Origin or anything like that.

Upvotes: 1

Related Questions