Javascript 如何将变量添加到 $.ajax({ url : " "});
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14048939/
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
How to add a variable to URL of $.ajax({ url : " "});
提问by ChristopherStrydom
I want the user to be able to change a part of the URL address to their post code. I have a text box and button which I am hoping will submit the value to the URL.
我希望用户能够将 URL 地址的一部分更改为他们的邮政编码。我有一个文本框和按钮,我希望它将值提交到 URL。
jQuery:
jQuery:
jQuery(document).ready(function($) {
$.ajax({
url : "http://SomeAddress.com/" + PostCode + ".json",
dataType : "jsonp",
success : function(parsed_json) {
HTML:
HTML:
<input type="text" id="GetPostCode" />
<button id="SetPostCode">Set This Post Code</button>
jQuery:
jQuery:
$("#SetPostCode").click(function() {
var PostCode = document.getElementById("GetPostCode").value;
$("#GetPostCode").val(" ");
return false;
});
I understand that the line
我明白这条线
$.ajax({
url : "http://api.wunderground.com/api/2508132ae0c7601a/geolookup/conditions/q/UK/" + PostCode + ".json",
does not work that way, but I didn't know what else to do. Could someone please show me what I need to do in order for this to work?
不能那样工作,但我不知道还能做什么。有人可以告诉我我需要做什么才能使其正常工作吗?
回答by cjds
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;
});
});
Above would work as PostCode is now global to the jQuery and can be accessed anywhere
上面可以工作,因为 PostCode 现在对 jQuery 来说是全局的,并且可以在任何地方访问

