I am attempting to do some ajax stuff which basically, depending on the results in the returned file (the php file) we 开发者_运维知识库have different actions in the javascript.
For example, say I'm doing the following:
$.ajax({
type: 'POST',
url: '/something.php',
data: 'something=something',
cache: false,
success: function(data) {
$('#something').html(data);
}
});
my something div will return something if its a success. Inside 'something.php' however, there could be a if statement like so:
if($_POST['something'] == 'not_something') {
// execute something here
} else {
// do something else
}
The thing is, what I'm executing, depending on the results is going to be javascript, and not php code. For example, currently I can achieve it by doing something like so:
if($_POST['something'] == 'not_something') {
echo '<script type="text/javascript">thissucks();</script>';
} else {
echo '<script type="text/javascript">atleastitworks();</script>';
}
But it just doesn't seem right to me. Is there a better way this sort of thing is accomplished?
Another scenario might be perhaps a ajax search function of some kind that does something different depending on whether there are results or not. This sort of thing. How does one do this without doing some really groovy inline javascript like I have done above?
You can use PHP's json_encode
to format an array that gives instruction back to the jQuery $.ajax()
function. Such as this:
<?php
if($_POST['something'] == 'not_something') {
echo json_encode(array('status'=>'thissucks'));
}
At which point in your $.ajax()
anonymous function for the success object literal looks like this:
$.ajax({
type: 'POST',
url: '/something.php',
date: 'something=something',
cache: false,
dataType: 'json', //this is important!
success: function(data) {
if(data['status']=='thissucks'){
//do something here
}
}
});
Best of luck!
UPDATE Forgot the all-important data-type attribute to make it eval() the json!
精彩评论