Is there a simple tutorial for this somewhere?
Ideally I'd like to have a textbox and a button, and when the user clicks the button, the textbox is sent to the server, which returns a value based on it.
The client then populates another textbox with the return value, but all without refreshing the page.
If it's possible, showing/hiding a开发者_开发问答 loading gif would be awesome too.
I'm not finding any simple tutorials for how to do this, can anyone point me in the right direction?
jQuery's Ajax method is your friend: http://api.jquery.com/category/ajax
HTML
<form id="myForm" action="/echo/html/" method="post">
<fieldset>
<textarea name="html" class="firstInput"></textarea>
<textarea class="secondInput"></textarea>
<input type="submit" value="GO!">
</fieldset>
</form>
<img src="http://vinofordinner.com/art/loading.gif" id="loader" />
CSS
#loader {
display: none;
}
jQuery
$(function(){
$('#myForm').submit(function(e){
e.preventDefault();
var $this = $(this),
data = $this.find('.firstInput').serialize(),
method = $this.attr('method'),
action = $this.attr('action');
$.ajax({
type: method,
url: action,
data: data,
beforeSend: function() {
$('#loader').show();
},
success: function(a){
$('.firstInput').val('');
$('.secondInput').val(a);
},
complete: function() {
$('#loader').hide();
}
});
})
})
Working example: http://jsfiddle.net/G4uw6/
Try googling for jQuery+AJAX.
There are lots of examples out there:
- http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
- http://visionmasterdesigns.com/tutorial-ajax-interface-menu-using-jqueryphp/
- http://www.ibm.com/developerworks/library/x-ajaxjquery.html
- http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html
You would do it like this:
$.ajax({
url: 'handlerscript.php',
type: 'POST',
data: {q: $('#theInput').val()},
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
},
beforeSend: function() {
$('.loadgif').show();
},
complete: function() {
$('.loadgif').hide();
}
});
To walk you through the function, the first parameter url
is set to the location of the resource you want to get a response from. The type
parameter sets the HTTP method used, it is most commonly set to either GET
(which is the default value) which appends any data being sent to the url or POST
which appends any data being sent to the request header. data
is an object or string containing the data to be sent to the requested page, it can either be in object form {param1: 'value1',param2: 'value2'}
or as url encoded string "param1=value1¶m2=value2"
. The success
method is called when a response has been received from the server which was successful. The beforeSend
method is called before the request is sent and the complete
method is called when a response has been received from the server regardless of the success of the request.
For more info, check out the Official jQuery API documentation of the jQuery.ajax() object
精彩评论