简体   繁体   中英

PHP json_encode data to jQuery for AJAX call

I am having a problem in using json_encode function.I am putting a simplified version of the problem here. Here is the file containing php and jquery code.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
<?php
$test = "xxxxxxx";
?>

<p onclick="testAjax()">Click here</p> 

<script>
var sendbody;

function testAjax(){
    sendbody = "<?php echo json_encode($test); ?>";
    $.ajax({
        type: 'POST',
        cache:false,
        url: 'testAjaxCall.php',
        data: {sendbody:sendbody},
        success:function(data){
            alert("1");
        },
        error:function(data){
            alert("0");
        }
      });
}
 </script>

And the ajax file simply contains

<?php
    echo "testAjax";
?>

When I use json_encode function, the jquery code written after using the json_encode function stops working and the ajax function shows neither the success message nor the error message. However if I write it as

sendbody = "<?php echo $test; ?>";

In this case the jquery code below this line works and shows success message.

When using json_encode , you don't have to quote the result, it's already quoted.

So change

sendbody = "<?php echo json_encode($test); ?>";

to

sendbody = <?php echo json_encode($test); ?>;

Otherwise you got:

 // this cause syntax error
 sendbody = ""xxxxxxx"";

First of all whenever you are expecting JSON to be returned to your AJAX call you have to tell it that by setting dataType: 'json', if not it tries to process it as text and obviously fails (your call is a success but the processing of the response isn't). The next best thing to do is use console.log(data) to get a better understanding of the response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM