[jQuery] Simple ajax script
Hi all,
i'm trying to make the script below work. It gets the results
serialized in json from django something like the dataset below.
Unfortunately i can't see anything displayed in the results div. I
suspect the json is not returning properly from the function or maybe
i made some gross mistake
Can anyone help?
Thanks,
Lorenzo
#############method returning json dataset############
def city_search(request, city_name):
city_list = serializers.serialize("json",
City.objects.filter(city__istartswith=city_name).order_by("city")[:10])
return HttpResponse(city_list, "text/javascript")
##########json produced by the method above#############
[{"pk": "8527", "model": "main.city", "fields": {"province": 41,
"city": "Fano", "region": 11}}, {"pk": "10193", "model": "main.city",
"fields": {"province": 67, "city": "Fano Adriano", "region": 13}}]
############Script##################
<html>
<head>
<title>Ajax test</title>
<script type="text/javascript" src="/site-media/jquery.js"></script>
<script type="text/javascript">
function find_cities(city_name)
{
$.getJSON("city_search/" + city_name + "/",
function(json)
{
eval("var dataset = " + json);
var result_text;
/*print the first 10 results*/
for(var i=0; i<10; i++)
{
result_text = result_text + dataset[i].fields["city"] + "<br />";
$("#results").text(result_text);
}
}
);
}
</script>
</head>
<body>
<form action="" method="post">
City search: <input type="text" name="city" value="" id="city"
onkeyup="find_cities($('#city').val());" />
<input type="submit" value="Submit" />
</form>
<div id="results">
</div>
</body>
</html>
_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/