如何在 URL 中传递 Javascript 变量?AJAX

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31321402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:32:05  来源:igfitidea点击:

How to pass Javascript variables inside a URL? AJAX

javascriptjqueryajaxurl

提问by Spyros_av

i am trying to pass the values of accesstoken and pageid inside the url that i use. Any ideas how to do it correctly?

我正在尝试在我使用的 url 中传递 accesstoken 和 pageid 的值。任何想法如何正确地做到这一点?

<script type="text/javascript">   
function makeUrl() {
    var accesstoken = "12345679|bababashahahhahauauuaua";
    var pageid =  "<?php echo $page_id;?>";
 $.ajax(
  {
    url: 'https://graph.facebook.com/?pageid/?access_token='+pageid+accesstoken,
 statusCode: {......

回答by Imran

Change

改变

url: 'https://graph.facebook.com/?pageid/?access_token='+pageid+accesstoken,

to

url: 'https://graph.facebook.com/?pageid='+pageid+'&access_token='+accesstoken,

回答by Matt

You can also use the "data" setting. This will convert it to a query string.

您还可以使用“数据”设置。这会将其转换为查询字符串。

<script type="text/javascript">   
function makeUrl() {
    var accesstoken = "12345679|bababashahahhahauauuaua";
    var pageid =  "<?php echo $page_id;?>";
 $.ajax(
  {
    url: 'https://graph.facebook.com/',
    data: 'pageid='+pageid+'&access_token='+accesstoken
 statusCode: {......

回答by KDP

 'https://graph.facebook.com/?pageid='+pageid+'&access_token='+accesstoken

回答by lucasfcosta

You can create your url using:

您可以使用以下方法创建您的网址:

function makeUrl() {
  var accesstoken = '12345679|bababashahahhahauauuaua';
  var pageid =  'example'
  return 'https://graph.facebook.com/?pageid=' + pageid + '&access_token=' + accesstoken;
}

And then pass it to your AJAX function.

然后将其传递给您的 AJAX 函数。

function doAjax(_url) {
  return $.ajax({
    url: _url,
    type: 'GET'
  });
}

doAjax(makeUrl());

And now an elegant way to handle your success callback:

现在有一种优雅的方式来处理您的成功回调:

doAjax(makeUrl()).success(function() {
  // this will be executed after your successful ajax request
});