简体   繁体   中英

Send message from php to ajax with 'echo json_encode' not working

I'm trying to send a message from php to ajax. I'm using echo json_encode to do it. When I do that, the website displays the arrays message. ( {"foo":"content of foo"} ). How can I get it to not display the message?

Also, the alerts from ajax don't get called.

Here's the code:

<?php
$myString = $_POST['data'];

if ($myString == "") {
    echo json_encode(
      array()
      );

} else if ($myString == "foo" {
    echo json_encode(
      array(
        'foo2' => 'this is the contents of foo'
        )
      );
} else if ($myString == "foo2") {
    echo json_encode(
      array(
        'foo2' => 'this is the contents of foo2'
        )
      );
}
?>


<script>
  var formData = new FormData($(this)[0]);
  $.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(response) {
      if (response.length == 0) {
          alert("empty");
      } else if (response.foo) {          
          alert("foo");
      } else if (respons.foo2) {
          alert("foo2");
      }          
    }
  });           
</script>

How can I get the array to not display on the website? And why are the ajax if statements not getting called?

You need to set the HTTP header at the top of the script so you can return son:

header('Content-type: application/json');

Your script is a little confusing. You can't return json AND html/javascript.

It's one or the other.

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