简体   繁体   中英

PhoneGap: load data from external sources

I would like to create a web app with phonegap (I'm trying on Android emulator), but I have a problem with the "same domain policy": is there any way to disable this restriction. I need to load html/json data from an external server (not my own, so I can't modify it), but when I try to get data JQuery returns an undefined object. Here's my code:

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="ISO-8859-1">
        <title>Title</title>
        <script type="text/javascript" src="js/jquery.min.js"></script>
        <script type="text/javascript">
            $.ajaxSetup ({
                cache: false
            });
            var ajax_load = "<img src='img/load.gif' alt='loading...' />";
            var jsonUrl = "external url";
                $("#result").html(ajax_load);
                $.getJSON(jsonUrl, function(json) {
                    var result = json.responseData;
                    $("#data").html("Result: " + result);
                });
        </script>
    </head>
    <body>
        <div id="data"></div>
    </body>
</html>

PhoneGapTestActivity

public class PhoneGapTestActivity extends DroidGap {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

Searching online and reading other questions, I tried to set the whitelist in the file phonegap.xml

<?xml version="1.0" encoding="UTF-8"?>
<phonegap>
    <access origin="*" subdomains="true" />
</phonegap>

But what I got is: "Result: undefined". Thanks a lot!

EDIT: After many tries, I noticed that the request works (I received the data), but there was some issues while accessing json data contents, but now it works!. Thanks for all answers.

There is no reason why it shouldn't work. I'm not a big user of jQuery but there are some things you can set to enable CORS.

A CORS POST request works from plain javascript, but why not with jQuery?

试试这个..我不知道它是否在这种情况下起作用,但是它对我有用。

<?xml version="1.0" encoding="utf-8"?>
<phonegap>
<access origin="http://127.0.0.1*"/>
<log level="DEBUG"/>
</phonegap>

经过多次尝试,我注意到请求有效(我收到了数据),但是访问json数据内容时出现了一些问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM