javascript - How to Simply Ajax Script (Removing duplicate code)? -


i want simplify following script, , create reuseable funciton, use with:

<span id="test"></span> <span id="abc"></span> <span id="123"></span> 

here now:

<script>   $(document).ready(function(){     var callajax = function(){       $.ajax({         method:'get',         url:'abctest.php',         success:function(data){           $("#test").html(data);         }       });     }     setinterval(callajax,1000);   });      $(document).ready(function(){     var callajax = function(){       $.ajax({         method:'get',         url:'getabc.php',         success:function(data){           $("#abc").html(data);         }       });     }     setinterval(callajax,1000);   });    $(document).ready(function(){     var callajax = function(){       $.ajax({         method:'get',         url:'123.php',         success:function(data){           $("#123").html(data);         }       });     }     setinterval(callajax,1000);   }); </script> 

as can see, need change url , #, create function:

function good(url,tag){     var callajax = function(){       $.ajax({         method:'get',         url:'url.php',         success:function(data){           $("#tag").html(data);         }       });     }     setinterval(callajax,1000);   } 

and rewrite script to:

<script> $(document).ready(good(abctest,test)); $(document).ready(good(getabc,abc)); $(document).ready(good(123,123)); </script> 

looks better. seems not easy. not working. how solve problem?

your there. need manually concatenate strings like

function good(url,tag){     var callajax = function(){       $.ajax({         method:'get',         url:url+'.php',         success:function(data){           $("#"+tag).html(data);         }       });     }     setinterval(callajax,1000);   } 

javascript not php variables can evaluated between double quotes.

also, need pass parameters in strings

$(document).ready(function(){     good('abctest','test');     good('getabc','abc');     good('123','123'); }); 

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -