开发者

Dynamic jQuery code: is there any way to include it in a file?

I have been developing and testing with inline jQuery. I am using CodeIgniter and the below refers to my views.

I have <script="text/javascript">JQUERY CODE</script> at the top of my page. Some of my code is dynamic in that it uses PHP 开发者_Python百科vars, e.g. when making an Ajax call, the URL is preceeded by <?php echo base_url(); ?>.

I have gotten the code working, but I want to put it in an external JS file for cleanliness. There seems to be no way I can think of to do this. Am I correct?

One aspect of my site is Google Maps. I use them all over the place. Again, parts of the code are dynamic, from PHP. Same question.

As a slight change, with the maps, I have many pages with many slightly different maps on them. Is there anyway to efficiently reuse map code, or am I going to have to have some duplicate code?


So are your customizations mostly just parameter replacements for things like google maps? If so, why not just have a function call that take a JSON object as a parameter. Have your backend serve some JSON data via an AJAX request, pass the data to the function, and you're done. Less JS code to download, and a much cleaner setup.

// site.js
function displayMap(params) {
  // code to display google map using values from params
  // for instance:
  var lat = params.lat;
  var long = params.long;
}  

To use this, do something like this:

$.get('ajax/mapdata.json?id=5', function(data) {
  displayMap(data);
  alert('Load was performed.');
});

Output JSON from your app by creating something like this:

{
  lat: 232
  long: 123
}

Hope that helps!


Well, do the same as you would do inside the page directly. Rename the .js file to a .php script, and include the same PHP code as you would before, in the .php file. Then, in the HTML file, use filename.php (not .js). The web server will invoke PHP on the script and send the browser the resulting JavaScript.


You can create a block of JSON data in your main page:

<script>
  var pageData = {
    something: 'whatever',
    somethingElse: [ 33.20, 19.02 ],
    moreStuff: false
  };
</script>

and then just reference the variable "pageData" from your script.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜