简体   繁体   中英

Call Ajax From another Ajax

I am using jQuery to do an autocomplete on a text field. Based on the user click from that auto complete I want to call another function that does an ajax request. How can this be accomplished.Here is first autocomplete function:

    function lookup(inputString) {
    if(inputString.length == 0) {
        // Hide the suggestion box.
        $('#suggestions').hide();
    } else {
        $.post("ajax/autocomplete.php", {queryString: ""+inputString+""}, function(data){
            if(data.length >0) {
                $('#suggestions').show();
                $('#autoSuggestionsList').html(data);
            }
        });
    }
} // lookup

function fill(thisValue) {
    $('#inputString').val(thisValue);
    setTimeout("$('#suggestions').hide();", 200);
}

and the second ajax call:

function showCar(str)
{
if (str=="")
{
document.getElementById("inputString").innerHTML="";
return;
} 
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("carchoice").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/getcar.php?q="+str,true);
xmlhttp.send();
}

and the initial call to the function from the form:

<input type="text" size="50" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();"/>
<div class="suggestionsBox" id="suggestions" style="display: none;">
            <img src="images/upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
            <div class="suggestionList" id="autoSuggestionsList">
                &nbsp;
            </div>

You can call it using these lines of code:

$('#autoSuggestionsList').children('div').click(function () {
    showCar(this.innerHTML);
});

Of course in case that you're putting each result in a new div which is child to #autoSuggestionsList :

<div class="suggestionList" id="autoSuggestionsList">
    <div>First result</div>
    <div>Second result</div>                
</div>

And a fiddle: http://jsfiddle.net/NaYzm/

Best regards!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM