I need a little help in my application design. Using Ajax I want to get some PHP resources consecutively but I don't think if it is good to retrieve them using JQuery $.ajax
method.
I think something like this means wrong design:
$开发者_运维百科.ajax({
url: SERVERURL+'index.php/home/checkAvailability',
datatype: 'text',
success: function(data){
if(data == 'unavailable'){
// do stuff
}
else{
$.ajax({
url: SERVERURL+'index.php/home/getWebTree/',
dataType: 'json',
success: function(data){
// do stuff
}
});
}
}
});
Can anybody give me a suggestion to get a better design? How can I do the same in a better way?
Thanks!
EDIT: like @arnorhs tell us, using async parameter could be a solution. But I'm still think that there are other solutions instead of using consecutive ajax calls.
EDIT2: checkAvailability
and getWebTree
are PHP functions using CodeIgniter that I've developed to get resources from an external server using Http_Request
object.
function checkAvailability() {
$this->load->library('pearloader');
$http_request = $this->pearloader->load('HTTP', 'Request');
$http_request->setURL('http://myurl');
$http_request->_timeout = 5;
$http_request->sendRequest();
$res = 'available';
if (!$http_request->getResponseCode())
$res = 'unavailable';
return $res;
}
Doing the calls all the same time
If you want to do all the ajax calls at the same time, you can simply call an ajax request right after the others. You could even assign them the same success handler. If you want a more "elegant" approach, I would do something like this:
// define a set of requests to perform - you could also provide each one
// with their own event handlers..
var requests = [
{ url: 'http://someurl', data: yourParams },
{ url: 'http://someurl', data: yourParams },
{ url: 'http://someurl', data: yourParams },
{ url: 'http://someurl', data: yourParams }
];
var successHandler = function (data) {
// do something
}
// these will basically all execute at the same time:
for (var i = 0, l = requests.length; i < l; i++) {
$.ajax({
url: requests[i].url,
data: requests[i].data,
dataType: 'text',
success: successHandler
});
}
.
Do a single request
I don't know your use case, but of course what you really should be trying to do is retrieve all the data you're retrieving in a single request. That won't put a strain on your server, the site/application will seem faster to the user and is a better long term approach.
I would try to combine checkAvailability
and getWebTree
into a single request. Instead of receiving the data in Javascript as text objects, a better approach would be to receive them as json data. Luckily PHP provides very easy functions to convert objects and arrays to json, so you'll be able to work with those objects pretty easily.
edit: small modifications in the PHP code now that I understand your use case better.
So something like this in the PHP/CI code:
function getRequestData () {
if (checkAvailability() == 'available') {
$retval = array (
'available' => '1',
'getWebTree' => getWebTree()
);
} else {
$retval = array (
'available' => '0'
);
}
header('Content-type: text/javascript; charset=UTF-8');
echo json_encode($retval););
}
And the Javascript code can then access those by a single ajax request:
$.ajax({
url: 'http://yoururl/getRequestData',
dataType: 'json',
success: function (jsonData) {
// we can now access the parameters like this:
if (jsonData.checkAvailability) {
// etc
}
//and of course do something with the web tree:
json.getWebTree
}
});
.
Execute the requests synchronously
If you set the async
parameter in the $.ajax options to false
the functions will be made in a synchronous fashion so your code halts until execution has been completed.. or as the documentation says:
asyncBoolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
See http://api.jquery.com/jQuery.ajax/
If you really need to make two calls you can be more expressive with Deffered that was introduced in jQuery 1.5.
$.when(checkAvailability())
.then(getWebTree())
.fail(function(message){
if(message === 'Not available!')
{
// do stuff
}
});
function checkAvailability(){
var dfd = $.Deferred();
$.ajax({
url: SERVERURL+'index.php/home/checkAvailability',
datatype: 'text',
success: function(data){
if(data == 'unavailable'){
dfd.reject("Not available!");
}
else{
dfd.resolve();
}
}
});
return dfd.promise();
};
function getWebTree(){
$.ajax({
url: SERVERURL+'index.php/home/getWebTree/',
dataType: 'json',
success: function(data){
// Do stuff
}
});
};
Check it out live at http://jsfiddle.net/jimmysv/VDVfJ/
It sounds like you could make use of the deferred object that's new to jquery 1.5
http://api.jquery.com/category/deferred-object/
Programming with commands that should be handled in queue live from callbacks, and this is just what you are doing.
You are defining a callback on the success of your request and send another request, once it is triggered and validated.
Nothing wrong with that.
The only thing, to keep it better maintainable, is defining the callbacks as functions before the call and just giving $.ajax the function names
function myFunc() {
//Do stuff
}
$.ajax{ {
success: myFunc
} );
精彩评论