如何将 ajax 结果用作可以在页面中任何地方打印的变量


How can I use ajax result as a variable that I can print everywhere in a page

这是我的ajax代码:

$("#to").change(function(){
  $.ajax({ 
  type: "POST",
  url: "<?php echo base_url();?>/index.php/sales/getPrice",             
  dataType: "html",       
  data: {'from' : $('#from').val() , to: $('#to').val()},    
  success: function(response){                
  //$(".location").html(response); 
 }
});             
});

我想使用 ajax 结果而不是 40。(以下代码附后)。

e: {
 price   : 40,
 category: 'Economy'
}

你想使用 ajax 调用返回的数据吗?因此,您可以在success部分中使用它:

$("#to").change(function(){
  $.ajax({ 
  type: "POST",
  url: "<?php echo base_url();?>/index.php/sales/getPrice",             
  dataType: "html",       
  data: {'from' : $('#from').val() , to: $('#to').val()},    
  success: function(response){                
     alert(respone.price);
     console.log(response);
 }
});             
});

在成功函数中使用console.log(response);,在浏览器的开发者控制台中获取数据。

var result = '';
$("#to").change(function(){
  $.ajax({ 
  type: "POST",
  async: false,
  url: "<?php echo base_url();?>/index.php/sales/getPrice",             
  dataType: "html",       
  data: {'from' : $('#from').val() , to: $('#to').val()},    
  success: function(response){                
      result = response;
 }
}); 
});

现在在您想要的位置使用该结果:

e: {
     price   : result,
     category: 'Economy'
  }