Make my jQuery Ajax script use CORS

Philip Kirkbride picture Philip Kirkbride · Jun 4, 2012 · Viewed 7.9k times · Source

I built an application which reads data via AJAX from an external website. It works fine but I found out in another question that if I want to package it for BlackBerry 7, with Webworks or Phonegap, I may need to use something called CORS.

How can I convert my following script to do the same thing except using 'CORS'?

    <script type="text/javascript">
        $("#page_all").live('pagebeforecreate', function() {
        $.get('http://mysite.com/mobile/data/data_all.php',function(data){
            $('.content').empty();
            $(data).find('market').each(function(){
                var $market = $(this);
                var html = '<div class="data">';                      
                html += '<div data-role="collapsible" data-collapsed="true" data-theme="b"><h3>' + $market.attr('date') + '</h3>';
                html += '</div>';
                $('#result').append(html).trigger( "create" );
                $('#result .loading').remove();
            });                        
        });
        });
    </script>

Answer

balexandre picture balexandre · Jun 4, 2012

you are probably hitting the domain (ontariosheep.org) from other domain name, and that brings the cross-domain into the poll.

CORS is just a way to solve this, and it has to be your server that hosts data_all.php that needs to be set to also have in the response header the property:

Access-Control-Allow-Origin: *

or, you can use the other common method called JSONP.

using JSONP method, you call should look like:

var url = "http://ontariosheep.org/mobile/data/data_all.php";
$.get(url + "?callback=?", function(data) {
    // your method body     
});