Can URL tell jQuery to run a function?

后端 未结 4 1532
滥情空心
滥情空心 2020-12-19 11:28

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 func

相关标签:
4条回答
  • 2020-12-19 12:02

    You can call a globally declared function using the window object:

    function bar(str) {
        alert("hello" + str);   
    }
    
    // assuming location is "http://example.com?bar"
    var fn = window.location.search.replace("?", "");
    window[fn](" Dovhakiin"); // 'hello Dovhakiin'
    
    0 讨论(0)
  • 2020-12-19 12:04

    I believe so:

    if(location.href == ""){
        xyz();
    else{
    
    }
    
    0 讨论(0)
  • 2020-12-19 12:05

    In the URL bar you can always put javascript:XYZ();

    Try that after this url loads: http://jsfiddle.net/maniator/mmAxY/show/

    0 讨论(0)
  • 2020-12-19 12:20

    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.

    0 讨论(0)
提交回复
热议问题