当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - PHP Javascript Uncaught SyntaxError: Unexpected token ILLEGAL

问题描述:

I have this PHP script and it does not work properly. What is the mistake?

<?php if(isset($success) || isset($failure)){?>

<script type="text/javascript">

$(document).ready(function(){

$('div.aler').css('display','block');

$("div.aler").html("<?php if($success){echo '<p class=\"success\">'.$success.'</p>';}elseif($failure){echo '<p class=\"failure\">'.$failure.'</p>';}; ?>");

setTimeout(function(){

$("div.aler").fadeOut("slow", function (){

$("div.aler").remove();

});

}, 5000);

});

</script>

<?php }

I think there must be a problem with quotes ". $failure has the message, but the Javascript does not put it in html div div.aler. I get this error message in the Chrome console:

Uncaught SyntaxError: Unexpected token ILLEGAL

Please help.

网友答案:

you forgot isset in below line, its required since your using "||" (OR) in your first if statement, php throwing an error and thats breaking your javascript

$("div.aler").html( "<?php if( $success ){ echo '<p class=\"success\">'.$success.'</p>';}elseif($failure){echo '<p class=\"failure\">'.$failure.'</p>';}; ?>");

change this to...

$("div.aler").html( "<?php echo ( isset( $success ) ) ? '<p class=\"success\">'.$success.'</p>' : '<p class=\"failure\">'.$failure.'</p>'; ?>");
网友答案:

The php output is not escaped for ", so instead of \" you have to use \\\" or \'.

Btw json_encode as a string would be much better...

$("div.aler").html(<?php
    if($success){
        echo json_encode('<p class="success">'.$success.'</p>');
    }
    elseif($failure){
        echo json_encode('<p class="failure">'.$failure.'</p>');
    };?>
);
网友答案:

You're trying to put it into div.alert...yet in your code you wrote "div.aler" you're missing a T...

网友答案:
$("div.aler").html("<p class='<?=$success? 'success' : 'failure'?>'><?=$success? $success : $failure?></p>");

And of course escaping $success and $failure before output.

分享给朋友:
您可能感兴趣的文章:
随机阅读: