繁体   English   中英

我的 ajax 请求不返回数据但返回一个空数组

[英]My ajax request does not return data but return an empty array

我想通过 ajax 将 js 中的数据传递给 php,但是即使我传递了一些数据,output 也是一个空数组。 请帮忙。

<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 请求的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

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

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

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"}

暂无
暂无

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

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