我之前问过这个问题,我正在尝试运行它,但在显示从javascript提示符到php的输入时遇到了问题,我在php部分得到了"UNDEFINED INDEX"。我想我几乎完成了我在网上看到的所有事情,但仍然没有运气。以下是我的javascript和ajax(包含script src="jquery.js"):
<script type="text/javascript">
var name = prompt('Please enter your name');
$.ajax({
url: 'index.php',
type: 'POST',
dataType: 'text',
data: name,
success: function(data){
console.log(data);
}
});
</script>
每次我试图提醒"数据"时,它只显示我为这个文件准备的一堆HTML代码。这是我的php文件。。
<?php
$response = $_POST['data'];
echo "Hello ".$response;
?>
我尝试过用post操作将我的php文件封装在一个表单中,但仍然出现了同样的错误。
提前感谢!
<script type="text/javascript">
var name = prompt('Please enter your name');
$.ajax({
url: 'index.php',
type: 'POST',
dataType: 'text',
data: {name : name},
success: function(data){
console.log(data);
}
});
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// get post data name from ajax
$response = $_POST['name'];
echo "Hello ".$response;
// stop executing other codes to test it
die();
}
?>
将您的数据选项data:name更改为data:{"data":name},
<script type="text/javascript">
var name = prompt('Please enter your name');
$.ajax({
url: 'test5.php',
type: 'POST',
dataType: 'text',
data: { "data":name},
success: function(data){
console.log(data);
}
});
</script>
,试试这对你有用
您必须使用名称-值对来传递数据
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
var name = prompt('Please enter your name');
$.ajax({
url: 'test.php',
type: 'POST',
dataType: 'text',
data: 'name='+name,
success: function(data){
console.log(data);
}
});
</script>
test.php
<?php
echo $_POST['name'];
将data: name
替换为data: JSON.stringify({"name": name})
,并使用contentType: "application/json"
而不是dataType:'text'
var name = prompt('Please enter your name');
$.ajax({
url: 'index.php',
type: 'POST',
contentType: "application/json",
data: JSON.stringify({"name": name}),
success: function(data){
console.log(data);
}
});
</script>
在php脚本中查询"name",而不是数据
<?php
$response = $_POST["name"];
echo "Hello ".$response;
?>
编辑:解决空数组问题
<?php
$temp = file_get_contents("php://input");
$_POST = json_decode($temp, true);
$response = $_POST["name"];
echo "Hello ".$response;
?>
另一个编辑:将contentType更改为不包括json
脚本:
var name = prompt('Please enter your name');
$.ajax({
url: 'index.php',
type: 'POST',
contentType: "application/x-www-form-urlencoded",
data: $.param({"name": name}),
success: function(data){
console.log(data);
}
});
</script>
在服务器中:
<?php
$response = $_POST["name"];
echo "Hello ".$response;
?>