URL可以告诉jQuery运行函数吗? [英] Can URL tell jQuery to run a function?

查看:77
本文介绍了URL可以告诉jQuery运行函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对URL和jQuery有疑问.

我可以指定URL来告诉jQuery运行函数吗?

例如 http://www.website.com/about.html?XYZ

运行功能XYZ();?

解决方案

您可以将代码放在该网页中,以检查URL上的查询参数,然后根据发现的内容调用所需的任何javascript函数. /p>

在您的特定示例中,简化版本将如下所示:

// code that runs when page is loaded:
if (window.location.search == "?XYZ") {
    XYZ();
}

或者,如果您希望它运行存在于此的任何函数,则可以从字符串中提取该函数并运行其中的任何名称.

// code that runs when page is loaded:
if (window.location.search.length > 1) {
    var f = window.location.search.substr(1);  // strip off leading ?
    try {
        eval(f + "()");  // be careful here, this allows injection of javascript into your page
    } catch(e) {/* handler errors here */}
}

允许在页面中运行任意javascript可能会或可能不会带来不希望的安全隐患. (如果可能的话)最好只支持您寻找并知道是安全的一组特定的预先存在的函数,而不是像第二个示例那样执行任意的javascript.

Have a question regarding URL and jQuery.

Can I specify URL to tell jQuery to run a function?

e.g http://www.website.com/about.html?XYZ

to run a function XYZ();?

解决方案

You can put code in that web page that examines the query parameters on the URL and then, based on what it finds, calls any javascript function you want.

In your particular example, a simplified version would be like this:

// code that runs when page is loaded:
if (window.location.search == "?XYZ") {
    XYZ();
}

or if you want it to run any function that is present there, you can extract that from the string and run whatever name is there.

// code that runs when page is loaded:
if (window.location.search.length > 1) {
    var f = window.location.search.substr(1);  // strip off leading ?
    try {
        eval(f + "()");  // be careful here, this allows injection of javascript into your page
    } catch(e) {/* handler errors here */}
}

Allowing arbitrary javascript to be run in your page may or may not have undesirable security implications. It would be better (if possible) to support only a specific set of pre-existing functions that you look for and know are safe rather than executing arbitrary javascript like the second example.

这篇关于URL可以告诉jQuery运行函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆