学习者驾驶警报!
我正在尝试从下面名为变量“name”&的表单中传输搜索字段内容。将其输入到flickr API JSON请求标记字段中(下面的第40行)。我已经尝试了各种方式来声明变量&似乎无法找到我在网上寻找的东西。我猜我不确切知道自己在寻找什么。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form id="search">
<p><input id="search-name" type="text" placeholder="Type Region Here"></p>
<p><input id="search-submit" type="submit" value="Search For Region"></p>
</form>
<div id="images"></div>
<script>
var name;
$("#search").submit(function(event){
event.preventDefault();
var name = $("#search-name").val();
console.log("Search Term Was: "+name);
return false;
});
$("#search").submit(function(event) {
(function() {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: name,
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 0 ) {
return false;
}
});
});
})();
});
</script>
</body>
</html>
有人会如此友好地帮助/让我朝着正确的方向前进吗?
答案 0 :(得分:1)
您不需要2个事件侦听器。
var name = $("#search-name").val();
会为name
创建本地范围,因此您无法在全球name
中找到价值。
以这种方式尝试:
$("#search").submit(function(event) {
event.preventDefault();
var name = $("#search-name").val();
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON(flickerAPI, {
tags: name,
tagmode: "any",
format: "json"
})
.done(function(data) {
$.each(data.items, function(i, item) {
$("<img>").attr("src", item.media.m).appendTo("#images");
if (i === 0) {
return false;
}
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
</head>
<body>
<form id="search">
<p>
<input id="search-name" type="text" placeholder="Type Region Here">
</p>
<p>
<input id="search-submit" type="submit" value="Search For Region">
</p>
</form>
<div id="images"></div>
</body>
</html>
&#13;
答案 1 :(得分:1)
运行jQuery似乎对我有用。您可以测试它,但也请注意我将闪烁的引用更改为加载为安全脚本:
var name;
$("#search").submit(function(event){
event.preventDefault();
name = $("#search-name").val();
alert("Search Term Was: "+name);
var flickerAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: name,
tagmode: "any",
format: "json"
})
.done(function( data ) {
alert('done');
$.each( data.items, function( i, item ) {
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 0 ) {
return false;
}
});
})
.fail(function() {alert('fail')});
});