如何将参数传递到PhoneGap应用程序中的本地页面?

时间:2013-04-03 07:39:42

标签: ios cordova parameters

在PhoneGap应用中,我们可以使用以下代码设置起始页。

self.viewController.wwwFolderName = @"www";
self.viewController.startPage = @"index.html";

但如果我想将参数传递给该页面,它将无效。

self.viewController.startPage = @"index.html?parameter=abc";

会导致NSURLErrorRedirectToNonExistentLocation错误。

是否有一种简单的方法可以将参数传递给本地页面?

3 个答案:

答案 0 :(得分:6)

在phonegap应用程序中,您无法通过向其传递参数来调用本地页面,因为系统会搜索与您传递的名称完全相同的文件。它不会将参数视为查询字符串。

Ex: when you say "index.html?param=abc", instead of calling page index.html with a
parameter called param having value abc. It calls the page "index.html?param=abc"
which doesn't exist in the system. Hence, the error.

解决此问题的最佳方法是将参数保存为调用页面中的本地存储,在下一页中使用它们并销毁它们。

Ex: In your calling JavaScript file, use:
window.localStorage.setItem('param', 'abc');

Now, in your called file, access the local storage and delete it
param abc = window.localStorage.getItem('param');

window.localStorage.removeItem('param');

希望有所帮助。

答案 1 :(得分:1)

编辑:适用于Cordova& Phonegap apps这个插件很有用http://goo.gl/TWN8wq所以你不必自己手动修改Android清单或iOS plist文件。 还有一个优点是能够在两个平台上使用相同的handleOpenURL()功能(你不能没有插件,handleOpenURL()只会是iOS的东西)

无论如何,手动:

要实现您的目标,您必须:

1 - 在xCode中注册自定义方案(如HelloWorld)和自定义网址(如customurl

2 - 在页面上放置一个链接,如<a href=”HelloWorld://customurl/username=James Bond”>HelloWorld</a>

3 - 使用函数username获取参数handleOpenURL的值,用于Phonegap&lt; 3.0或OpenURL用于Phonegap 3+,例如:

function handleOpenURL(url) {

                    //Here we can parse the url .

                    var link = url.split(‘=’);

                    var username = link[1];

                    alert(username);

}

有一个完整的教程如何做here(iOS),这是我从中获取的所有内容。

对Sourabha Kumar Sahoo的信用

答案 2 :(得分:0)

如果我是你,我会通过您将创建的插件方法将所有信息传递给javascript(即plugin.GetQueryString())您可以创建一个通用插件方法,将所有查询参数返回为一个字符串,然后您可以使用以下方法在javascript中处理它:

function getQueryParams(qs) {
    var params = {},
    tokens,
    re = /[?&]?([^=]+)=([^&]*)/g;

    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
        = decodeURIComponent(tokens[2]);
    }

    return params;
}

window.$_GET = getQueryParams(plugin.GetQueryString());

因此,您将获得一个很好的数据结构,其中包含您可以按名称访问的所有GET参数。

相关问题