如何在$.ajax({ url: " "});中添加变量?

8
我希望用户能够更改URL地址的一部分,以输入他们的邮政编码。我有一个文本框和按钮,希望它能够将值提交到URL。
jQuery:(以下是 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",

这不是那样工作的,但我不知道还能怎么做。请问有人可以告诉我需要怎么做才能使其正常工作吗?

2
只有一种情况会导致这个无法工作,那就是PostCode不是全局的。如果是,你就可以进行排序了。 - cjds
2
为什么不在单击处理程序内的var PostCode行后执行$.ajax呢? - BalusC
1
+1 @CarlSaldanha,你在点击函数中设置了PostCode变量,因此无法从其他地方访问它。 - wakooka
那很简单...谢谢大家。 - ChristopherStrydom
1个回答

9
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中,以便每次刷新页面时都是他们设置的值吗? - ChristopherStrydom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接