jQuery AJAX - receive multiple data
I use Wordpress, PHP, jQuery and AJAX.
I can get data from PHP through an AJAX call, like this:
开发者_开发问答$.ajax({
type: "POST",
url: "<?php echo get_bloginfo('url'); ?>/?addmod_ajax=1",
data: "action=load&type=part",
success: function(data){
alert(data);
}
});
When I have received the data I also want to know how it went. The "data" contains HTML and I also want error codes like "success" or "not-found".
How do I solve it the best way?
Wordpress
Because I use Wordpress I need to call a AJAX trigger (in the url). If I could keep that intact it would be nice.
$.ajax({
type: "POST",
url: "<?php echo get_bloginfo('url'); ?>/?addmod_ajax=1",
data: "action=load&type=part",
success: function(data){
alert(data);
},
failure: function(){
alert('failed');
}
});
You could add a failure handler to see if the ajax request is failed, but other than that, if want a different return value, you will have to change the result of the function you are calling on the backend, or create a new similar function that instead of just returning the html, returns a json encoded array with the first element being found or not found, and the second element being the html.
Edit: Appended comment to complete answer and format code.
at the place where you echo 'your result', you can echo instead
json_encode(array('success'=>true,'html'=>$yourData));
and in your ajax call, add
dataType:'json'
then you can access the success and html values in your success handler.
I usually just return an array or dict with one value designated as the state.
$.get(url,data,function(data) {
if (data[0]=='parseError') { //could also be data.state
$("#formError").html("You have entered an invalid value.").show();
}
else if (data[0]=='permissionDenied') {
$("#formError").html("You do not have permission to edit this.").show();
}
else {
$("#formSuccess").html("Your changes have been saved");
}
});
Those examples may not be the best (permission denied and parsing errors could be handled on the front end). Still the concept is solid.
精彩评论