简体   繁体   中英

How can i get request parameters through ajax in js file?

I have send the ajax request to the js file like below

 function add(lt,ln)

{

    $.ajax({

          type: 'get',
            url: "js/abc.js",
            data: {action: "addme", lt: lt,ln:ln},
            async: false,
            success: function(data){

            }
            });



}

Now the question is i need lt and ln variable in abc.js file. How can i get these variable when this request is send i want n abc.js file

if(action==addme)
{
var lt=set value which is comng from ajax request.
}

You cannot do it in JS file

After sending Ajax GET request, url will become ./js/abc.js?action=action&lt=lt . Hence, you are sending parameters to JS file & JS file will not execute or change automatically because .js extension. except: when you changed server configuration

Another way is: to change your file extension to .php or .html or whatever(JavaScript output in PHP file)

Like:

function add(lt,ln)
{
    $.ajax({
          type: 'get',
          url: "js/abc.php",
          data: {action: "addme", lt: lt,ln:ln},
          async: false,
          success: function(data){
           ///Do something with 'data'
           ///'data': var lt=lt; alert(lt);
            }
            });
}

js/abc.php :

<?php
   $action = $_GET["action"];
   if($action=="addme"){ //check if action=addme
      echo "var lt=".$_GET["lt"].";"; //Adding variable coming from Ajax request
    }?>
 alert(lt);

Try to understand code. Hope it will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM