到处寻找尝试解决这个简单的问题。我在jQuery中使用Ajax调用尝试用来自API的新数据替换'#newevent'。我能够成功检索数据,但无法用每次调用替换数据。会发生什么是新数据只是添加到旧数据的底部。我尝试过使用$('#newevent')。html('')和$('#newevent')。empty()但没有成功。任何建议将不胜感激!感谢
的index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="query" action="away.php" method="get">
<label for="location">Location:</label>
<input type="text" id="location" name="location"/>
<input type="submit" value="submit" />
</form>
<h1>Welcome to Event Planner</h1>
<h2>The site where will help you plan upcoming events with what the weather is doing for that day!</h2>
<section id="container">
<div id="newevent">
</div>
</section>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="templates/script.js"></script>
</body>
</html>
scripts.js中
$(document).ready(function(){
var newContent='';
var $content=$('#newevent');
$("#query").submit(function (e){
e.preventDefault();
var data = $(this).serialize();
var url="http://api.eventful.com/json/events/search?app_key=XXXXXXXXX&";
var url= url.concat(data);
console.log(url);
$.ajax({
url:url,
dataType: 'jsonp',
success:function(response)
{
$content.html("");
$content.html(function()
{
for(var i=0; i<response.events.event.length; i++)
{
newContent+=response.events.event[i].description;
}
return newContent;
}).hide().fadeIn(400);
}
});
});
});
答案 0 :(得分:3)
问题是newContent
没有被重置,通过newContent = "";
在每次调用时将其设置为空字符串:
$(document).ready(function () {
var newContent = '';
var $content = $('#newevent');
$("#query").submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
var url = "http://api.eventful.com/json/events/search?app_key=XXXXXXXXX&";
var url = url.concat(data);
console.log(url);
$.ajax({
url: url,
dataType: 'jsonp',
success: function (response)
{
newContent = ""; //Add this
$content.html("");
$content.html(function ()
{
for (var i = 0; i < response.events.event.length; i++)
{
newContent += response.events.event[i].description;
}
return newContent;
}).hide().fadeIn(400);
}
});
});
});
或者@Jamiec在他的评论中指出我们只在html函数回调中声明它:
$(document).ready(function () {
var $content = $('#newevent');
$("#query").submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
var url = "http://api.eventful.com/json/events/search?app_key=XXXXXXXXX&";
var url = url.concat(data);
console.log(url);
$.ajax({
url: url,
dataType: 'jsonp',
success: function (response)
{
$content.html(function ()
{
var newContent = "";
for (var i = 0; i < response.events.event.length; i++)
{
newContent += response.events.event[i].description;
}
return newContent;
}).hide().fadeIn(400);
}
});
});
});