如何在不刷新页面的情况下将数据从PHP文件传递回原始文件?
我试图让PHP文件的输出显示在包含表单的原始页面中,而不必刷新页面 我目前正在使用AJAX,但无法将提交的PHP文件的值传递回index.PHP页面-这需要在不刷新页面的情况下完成 总体如何在不刷新页面的情况下将数据从PHP文件传递回原始文件?,php,jquery,ajax,forms,Php,Jquery,Ajax,Forms,我试图让PHP文件的输出显示在包含表单的原始页面中,而不必刷新页面 我目前正在使用AJAX,但无法将提交的PHP文件的值传递回index.PHP页面-这需要在不刷新页面的情况下完成 总体 用户输入一些数据并提交表单 该数据通过AJAX传递到PHP文件 通过PHP文件操作的一些数据片段,然后在不刷新页面的情况下,被回显到原始的index.html文件中 在下面,您将找到我目前用来尝试实现这一点的代码 index.php <form> <input type="text
- 用户输入一些数据并提交表单
- 该数据通过AJAX传递到PHP文件
- 通过PHP文件操作的一些数据片段,然后在不刷新页面的情况下,被回显到原始的index.html文件中
<form>
<input type="text" name="hi">
<input type="submit">
</form>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
});
});
});
</script>
<?php
echo "Hello";
$name = $_POST['hi'];
echo $name . "This is a test";
?>
$(函数(){
$('form')。关于('submit',函数(e){
e、 预防默认值();
$.ajax({
键入:“post”,
url:'post.php',
数据:$('form')。序列化(),
});
});
});
post.php
<form>
<input type="text" name="hi">
<input type="submit">
</form>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
});
});
});
</script>
<?php
echo "Hello";
$name = $_POST['hi'];
echo $name . "This is a test";
?>
我将感谢任何帮助,谢谢 将“success”添加到对象中,并将参数传递给函数。这将保存php文件的结果
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function(results) {
console.log(results);
}
});
这样做的目的是,在一个成功的ajax调用中,将从
post.php
文件发送的所有内容存储到results
变量中。在这种情况下,它将是$name
和“这是一个测试”。这个简单的解决方案怎么样。只要将此代码复制并粘贴到一个名为index.php的文件中,您在输入字段中输入的任何文本都将由php输出。希望有帮助
<?php
$data = array();
if(isset($_POST['userText']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = 'The data you entered is: ' . $_POST['userText'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" name="hi" id = "someID">
<input type="submit" id = "sendInfo">
</form>
<div id = "random"></div>
<script type = "text/javascript">
$("#sendInfo").click(function(){
var someText = document.getElementById("someID").value;
var userText = JSON.stringify(someText);
$.ajax({
url: "index.php",
method: "POST",
dataType: "json",
data: {userText: userText},
success: function (result) {
console.log(result);
$("#random").html(result);
}
});
return false;
});
</script>
</body>
</html>
$(“#发送信息”)。单击(函数(){
var someText=document.getElementById(“someID”).value;
var userText=JSON.stringify(someText);
$.ajax({
url:“index.php”,
方法:“张贴”,
数据类型:“json”,
数据:{userText:userText},
成功:功能(结果){
控制台日志(结果);
$(“#random”).html(结果);
}
});
返回false;
});