【问题标题】:My ajax request does not return data but return an empty array我的 ajax 请求不返回数据但返回一个空数组
【发布时间】:2020-07-25 09:07:52
【问题描述】:

我想通过ajax将数据从js传递到php,但是即使我传递了一些数据,输出也是一个空数组。请帮忙。

<html>
  <head>
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  </head>
  <body>

  </body>
  <script>
      $.ajax({
        url:"trialphp.php",
        data:{name:"bhanu",
              caste:"arora"},
        success:function(res){
          console.log(res);
        }
      });
    </script>
</html>```

**trialphp.php**
<?php
echo(json_encode($_GET));
?>

【问题讨论】:

  • 方法在哪里? $.ajax({ url:"trialphp.php",method:'POST'method:'GET' 并在方法后添加 type:'json'
  • 您的代码运行良好。所以不确定你的问题是什么。

标签: javascript php html ajax


【解决方案1】:

您需要定义要用于此 ajax 请求的 method 以及您需要定义您的 dataType

<script>
  $.ajax({
    url:"trialphp.php",
    method: 'get', //or post
    dataType: 'json',
    data:{name:"bhanu",
          caste:"arora"},
    success:function(res){
      console.log(res);
    }
  });
</script>

在你的情况下,你返回一个数组,所以dataType 应该是json,如果你想回显一个非数组变量,那么在dataType 中输入text

【讨论】:

  • 方法默认是GET。
  • 你是对的@TimBrownlaw,只是为了演示定义使用哪种方法,所以我在method写了评论
  • 感谢你们!但我在移动设备中使用它,您有任何建议如何在移动设备中成功运行 Ajax。
【解决方案2】:

这并不是真正的答案,而是您的代码有效的演示。

我将您的代码设置如下...

index.php

<html>
<head>
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<h1>This is an AJAX Test</h1>
</body>
<script>
    $.ajax({
        url: "trialphp.php",
        data: {
            name: "bhanu",
            caste: "arora",
            itworks:"success"
        },
        success: function (res) {
            console.log(res);
        }
    });
</script>
</html>

trialphp.php

<?php
echo(json_encode($_GET));

在 Firefox 下的控制台中,我得到...

{"name":"bhanu","caste":"arora","itworks":"success"}

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    相关资源
    最近更新 更多