[英]My ajax request does not return data but return an empty array
I want to pass data from js to php through ajax, but the output is an empty array even if I passed some data.我想通过 ajax 将 js 中的数据传递给 php,但是即使我传递了一些数据,output 也是一个空数组。 please help with this.
请帮忙。
<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));
?>
You need to define which method
you are going to use for this ajax request as well as you need to define your dataType
.您需要定义要用于此 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>
in your case you're returning an array so dataType
should be json
, if you want to echo a non array variable then type text
in dataType
在您的情况下,您要返回一个数组,因此
dataType
应该是json
,如果要回显非数组变量,则在dataType
中键入text
This isn't really an answer but a demonstration that your code works.这不是真正的答案,而是您的代码有效的演示。
I setup your code as follows...我将您的代码设置如下...
index.php 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>
And trialphp.php is和trialphp.php是
<?php
echo(json_encode($_GET));
And in my console under firefox I get...在 firefox 下的控制台中,我得到...
{"name":"bhanu","caste":"arora","itworks":"success"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.