简体   繁体   English

使用“ echo json_encode”将信息从php发送到ajax

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

I'm trying to send a message from php to ajax. 我正在尝试从php向ajax发送消息。 I'm using echo json_encode to do it. 我正在使用echo json_encode来做到这一点。 When I do that, the website displays the arrays message. 当我这样做时,网站将显示arrays消息。 ( {"foo":"content of foo"} ). {"foo":"content of foo"} )。 How can I get it to not display the message? 如何获取显示消息的信息?

Also, the alerts from ajax don't get called. 而且,ajax的警报不会被调用。

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? 以及为什么没有调用ajax语句?

You need to set the HTTP header at the top of the script so you can return son: 您需要在脚本顶部设置HTTP标头,以便返回son:

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

Your script is a little confusing. 您的脚本有点混乱。 You can't return json AND html/javascript. 您无法返回json和html / javascript。

It's one or the other. 是一个或另一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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