开发者

how to send an object from one js file to another js file?

Suppose, a webpage have only a hyperlink. I am not using any form. If user click on that link. the page will be redirected to an another page with an JSON object. I have to get that object from js script file. How can I send an object from one js to another js file ? I can't use any session, cookies, jsp file.

I can use query string, aja开发者_如何学JAVAx or jquery.

Is it possible to send an object by querystring ?

how can I get object from querystring ?


You can use the jQuery QueryString Plugin: http://plugins.jquery.com/project/query-object

The usage seems pretty simple and there is a good example on the plugin page.

Other than that you could use regexes to parse the QueryString, but I would probably go with the plugin approach if I were you.


You could pass the object properties individually by querystring , then rebuild the object on the otherside.


Here is an simple example where a javascript object is sent from one web page to another. In this case the object is sent in the GET parameters of the request. The first example will send the object when the link is clicked

<html>
 <head>
  <script src="../prototype.js" type="text/javascript"></script>
  <script type="text/javascript">
    Event.observe(window, 'load', function() { 
      sendObject=function(el){
        var myObj = eval('(' + this.readAttribute('obj') +')');
        window.location = 'test.php?obj='+ this.readAttribute('obj');
      }
      $('sendobj').observe('click',sendObject);
    });
  </script>
 </head>
 <body>
  <div id="sendobj" foo="bar" obj="{'id':'3','name':'fred'}">
   Send the object
  </div>
 </body>
</html>

And the file test.php file can process the object and when the page loads the object is available.

<html>
 <head>
  <script src="../prototype.js" type="text/javascript"></script>
  <script type="text/javascript">
    Event.observe(window, 'load', function() { 
      var person=<?php echo $_GET['obj'] ?>;
      //and now the object is available in the page that we arrived at
      alert('My name is ' + person.name);
    });
  </script>
 </head>
 <body>
The object is here now  
 </body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜