简体   繁体   English

在AJAX请求中未收到任何数据

[英]no data received from in AJAX request

I test my first AJAX form, but when I submit my form the alert message just shows '2'. 我测试了我的第一个AJAX表单,但是当我提交表单时,警告消息仅显示为“ 2”。 I search for sending ajax data to the same page and I found, that I can do that, but URL is optional. 我搜索将ajax数据发送到同一页面,发现可以这样做,但是URL是可选的。

my PHP code: 我的PHP代码:

 <html>
    <body>
    <form action="index.php" method="post">
    <input name="name" type="text" />
    <input type="submit" value="submit" name="submit">
    </form>

    <?php
    if(isset($_POST["name"]))
    {
    $data="test string";
    echo json_encode($data);
    }



?>
<script src="jquery-2.1.0.min.js"></script>
<script src="ajax.js"></script>
</body>
</html>

my AJAX code: 我的AJAX代码:

$(document).ready(function() {
$('form').submit(function(event) {
$.ajax({
            type        : 'POST', 
            url         : 'index.php', 
            data        : $(this).serialize(), 
            dataType    : 'json',
            encode      : true

        })

    .done(function(data) {
    alert(1);
    })
    .fail(function(data) {
        alert(2);
            });
            event.preventDefault();

});


});

I don't know where I go wrong? 我不知道哪里出问题了?

It's better to delegate page generation and json-response generation to different pages. 最好将页面生成和json响应生成委派给不同的页面。 At least you should isolate it, because the following part of page also ends up in ajax-response: 至少您应该隔离它,因为页面的以下部分也以ajax-response结尾:

<html>
  <body>
    <form action="index.php" method="post">
      <input name="name" type="text" />
      <input type="submit" value="submit" name="submit">
    </form>
    ...
    <script src="jquery-2.1.0.min.js"></script>
    <script src="ajax.js"></script>
  </body>
</html>

Modifiyng your script, you can do something like that: 修改脚本,您可以执行以下操作:

<? 
if(isset($_POST["name"]))
{
  // And don't forget to specify content type!
  header("Content-type: application/json");
  $data="test string";
  echo json_encode($data);
} else { 
?>
<html>
  <body>
    <form action="index.php" method="post">
      <input name="name" type="text" />
      <input type="submit" value="submit" name="submit">
    </form>
    <script src="jquery-2.1.0.min.js"></script>
    <script src="ajax.js"></script>
  </body>
</html>
<? } ?>

And, for future, please, post the exact request and response information in your questions, which you can get on Network page for developer tools of chrome, for example. 并且,为了将来,请在您的问题中发布确切的请求和响应信息,例如,您可以在网络页面上获得chrome开发人员工具的信息。

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

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