[EMAIL PROTECTED] wrote:
> 
> On 1/22/07, Lorenzo Bolognini <[EMAIL PROTECTED]> wrote:
> Fixed for cycle:
> 
>                       for(i=0;i<10;i++)
>                       {
>                               var results = $('#results').val() +
> $('#results').text(json[i].fields['city'] + "<br />");
>                               $('#results').text(results);
>                       }
> 
> 
One of the problems in your for cycle is when you get less then 10 json
objects.
This will generate error's and in effect the results div will not be filled.
I replaced the limit 10 with json.length. In your django-code you could
limit the returned cities bij using slicing: add a [:10] to the
django-query-object.

I changed your original code, it now uses more jquery-calls so the body-html
is cleaner and not filled with javascript-calls. 
Further ideas for extending the code would be adding a timeout for the keyup
handler to prevent hitting the server 
5 times when the user types in a word of 5 letters at normal typing-speed. I
recall using a 400 millisecs timeout gave good results.

=====city.html================
<html>
<head>
<title>Ajax test</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("#city").keyup(function(){
        find_cities($(this).val());
    });
});

function find_cities(city_name) {
    var city_name = city_name;
    $.getJSON("city_json.txt", function(json) {
        result_html = ''
        for( i=0;i<json.length;i++) {
            result_html += json[i].fields['city'] + "<br />";
        }
        $('#results').html(result_html);
    });
}

</script>
</head>
<body>

<form action="" method="post">
        City search: <input type="text" name="city" value="" id="city" />
        <input type="submit" value="Submit" />
</form>

<div id="results">
</div>

</body>
</html>

=========city_json.txt===================
[{"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}}]

-- 
View this message in context: 
http://www.nabble.com/Simple-ajax-script-tf3051317.html#a8651419
Sent from the JQuery mailing list archive at Nabble.com.


_______________________________________________
jQuery mailing list
[email protected]
http://jquery.com/discuss/

Reply via email to