【问题标题】:How to add a variable to URL of $.ajax({ url : " "});如何在 $.ajax({ url : " "}); 的 URL 中添加变量
【发布时间】:2012-12-12 12:06:37
【问题描述】:

我希望用户能够将 URL 地址的一部分更改为他们的邮政编码。我有一个文本框和按钮,希望将值提交给 URL。

jQuery:

jQuery(document).ready(function($) {
    $.ajax({ 
        url : "http://SomeAddress.com/" + PostCode + ".json",
        dataType : "jsonp",
        success : function(parsed_json) {

HTML:

<input type="text" id="GetPostCode" />
<button id="SetPostCode">Set This Post Code</button>

jQuery:

$("#SetPostCode").click(function() {
    var PostCode = document.getElementById("GetPostCode").value;
    $("#GetPostCode").val(" ");
    return false;
});

我明白这条线

$.ajax({ 
    url : "http://api.wunderground.com/api/2508132ae0c7601a/geolookup/conditions/q/UK/" + PostCode + ".json",

那样不行,但我不知道还能做什么。有人可以告诉我我需要做什么才能使其正常工作吗?

【问题讨论】:

  • 唯一不起作用的原因是 PostCode 不是全球性的......如果它是你的排序
  • 为什么不在点击处理程序中var PostCode 行之后的$.ajax 呢?
  • +1 @CarlSaldanha 您在 click 函数中设置了 PostCode 变量,因此您无法从其他地方访问它。
  • 那很简单...谢谢大家

标签: javascript jquery ajax url input


【解决方案1】:
jQuery(document).ready(function($) {

   var PostCode=1;
   $.ajax({ url : "http://SomeAddress.com/"+PostCode +".json",
   dataType : "jsonp"
   //.... more stuff
  });


  $("#SetPostCode").click(function() {
     PostCode = document.getElementById("GetPostCode").value;
     $("#GetPostCode").val(" ");
     return false; 
  });

});

上面可以工作,因为 PostCode 现在对 jQuery 来说是全局的,并且可以在任何地方访问

【讨论】:

  • 非常感谢。你知道如何将这个值保存在 cookie 中,以便他们每次刷新页面时设置的值?
猜你喜欢
  • 2019-07-26
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
  • 2017-06-15
  • 1970-01-01
相关资源
最近更新 更多