简体   繁体   中英

pass parameters to ajax call in javascript

Currently I'm editing a string, query, to pass to my .getJSON function. Its starting to get messy, and I'm wondering if there is a better way to pass parameters in javascript?

  var twitter = {
   query: "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=" + user_name + "&count=" + count + "&callback=?",
   tweets: 3
   };

 $.getJSON(twitter.query, 
 function(json) {

       console.log(json);
       } 
 });
})

$.getJSON() optionally accepts a data argument which will build that string for you:

var url = 'https://api.twitter.com/1/statuses/user_timeline.json?callback=?';

var parameters = {
  include_entities: true,
  include_rts: true,
  screen_name: user_name,
  count: count
}

$.getJSON(url, parameters, function(json) {
  console.log(json);
});

Assuming you're using jQuery.getJSON , you can pass the parameters as an object, separate from the URL:

$.getJSON('https://api.twitter.com/1/statuses/user_timeline.json', {
        include_entities:true,
        include_rts:true,
        screen_name:user_name,
        count:count
        /* I excluded callback */
    }, function(json) {
        console.log(json);
    }
);

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