Make my jQuery Ajax script use CORS

℡╲_俬逩灬. 提交于 2019-12-08 01:38:30

问题


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>

回答1:


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     
});



回答2:


You could turn on CORS in jquery specifically with

$.support.cors = true;

Also, make sure to configure your widget config correctly (config.xml) and add

<access uri="*" /> 

or at least

<access uri="ontariosheep.com" />


来源:https://stackoverflow.com/questions/10881868/make-my-jquery-ajax-script-use-cors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!